Skip to main content

tsh/backends/
bash.rs

1//! Bash 3.2 code generation for the typed IR.
2//!
3//! Generated functions communicate return values through `__tsh_backend_result`.
4//! Calls are emitted directly, rather than through command substitutions, so
5//! assignments and object mutations survive nested and recursive calls.
6
7use std::collections::{HashMap, HashSet};
8
9use crate::{
10    backends::Backend,
11    compiler::diagnostics::CompileError,
12    ir::{Class, Command, Expr, ExprKind, Field, Function, Method, Place, Program, Stmt, Type},
13};
14
15/// The Bash 3.2 backend.
16#[derive(Debug, Default, Clone, Copy)]
17pub struct Bash;
18
19/// A descriptive alias for callers that prefer the longer backend name.
20pub type BashBackend = Bash;
21
22impl Backend for Bash {
23    fn emit(&self, program: &Program) -> Result<String, CompileError> {
24        validate_program(program)?;
25        let metadata = Metadata::new(program);
26        let mut output =
27            String::from("#!/usr/bin/env bash\n# Generated by tsh. Requires Bash 3.2 or newer.\n");
28        if !program.functions.is_empty() || !program.classes.is_empty() {
29            output.push_str("__tsh_backend_result=''\n");
30        }
31        if !program.classes.is_empty() {
32            output.push_str("__tsh_backend_next_object_id=0\n");
33        }
34        for name in &metadata.global_order {
35            if metadata.guarded_globals.contains(name) {
36                output.push_str(&format!("{}=0\n", ready_flag(name)));
37            }
38        }
39        if !metadata.guarded_globals.is_empty() {
40            output.push('\n');
41        }
42        for class in &program.classes {
43            for field in &class.fields {
44                output.push_str(&format!(
45                    "declare -a {}\n",
46                    field_array(&class.name, &field.name)
47                ));
48            }
49        }
50        if !program.classes.is_empty() {
51            output.push('\n');
52        }
53
54        let mut next_temp = 0usize;
55        for function in &program.functions {
56            output.push_str(&emit_function(function, None, &metadata, &mut next_temp)?);
57            output.push('\n');
58        }
59        for class in &program.classes {
60            output.push_str(&emit_constructor(class, &metadata, &mut next_temp)?);
61            output.push('\n');
62            for method in &class.methods {
63                output.push_str(&emit_method(class, method, &metadata, &mut next_temp)?);
64                output.push('\n');
65            }
66        }
67
68        let mut top = Writer::new(&metadata, &mut next_temp, ReturnMode::TopLevel);
69        top.emit_statements(&program.body)?;
70        output.push_str(&top.code);
71        Ok(output)
72    }
73}
74
75#[derive(Debug, Clone)]
76struct Value {
77    /// A single shell word. Expansions in this string are already quoted.
78    word: String,
79    /// An arithmetic expression made only from a literal or a compiler-owned
80    /// variable name. Strings deliberately have no arithmetic form.
81    arithmetic: Option<String>,
82    /// A compiler-owned variable name when the value is stored in a variable.
83    name: Option<String>,
84    ty: Type,
85}
86
87impl Value {
88    fn new(word: impl Into<String>, arithmetic: Option<String>, ty: Type) -> Self {
89        Self {
90            word: word.into(),
91            arithmetic,
92            name: None,
93            ty,
94        }
95    }
96
97    fn named(mut self, name: impl Into<String>) -> Self {
98        self.name = Some(name.into());
99        self
100    }
101
102    fn arithmetic(&self) -> Result<&str, CompileError> {
103        self.arithmetic.as_deref().ok_or_else(|| {
104            CompileError::plain("Bash backend expected a numeric or boolean IR value")
105        })
106    }
107}
108
109#[derive(Debug, Clone)]
110struct Metadata<'a> {
111    classes: HashMap<&'a str, &'a Class>,
112    methods: HashMap<(&'a str, &'a str), bool>,
113    global_order: Vec<&'a str>,
114    guarded_globals: HashSet<&'a str>,
115}
116
117impl<'a> Metadata<'a> {
118    fn new(program: &'a Program) -> Self {
119        let mut classes = HashMap::new();
120        let mut methods = HashMap::new();
121        let mut global_names = HashSet::new();
122        let mut global_order = Vec::new();
123        for class in &program.classes {
124            classes.insert(class.name.as_str(), class);
125            for method in &class.methods {
126                methods.insert(
127                    (class.name.as_str(), method.function.name.as_str()),
128                    method.is_static,
129                );
130            }
131        }
132        for statement in &program.body {
133            if let Stmt::Let { name, .. } = statement
134                && global_names.insert(name.as_str())
135            {
136                global_order.push(name.as_str());
137            }
138        }
139        let mut referenced_globals = HashSet::new();
140        for function in &program.functions {
141            collect_statement_variables(&function.body, &mut referenced_globals);
142        }
143        for class in &program.classes {
144            for field in &class.fields {
145                if let Some(initial) = &field.initial {
146                    collect_expression_variables(initial, &mut referenced_globals);
147                }
148            }
149            collect_statement_variables(&class.constructor.body, &mut referenced_globals);
150            for method in &class.methods {
151                collect_statement_variables(&method.function.body, &mut referenced_globals);
152            }
153        }
154        let guarded_globals: HashSet<&str> = global_names
155            .iter()
156            .copied()
157            .filter(|name| referenced_globals.contains(*name))
158            .collect();
159        global_order.retain(|name| guarded_globals.contains(name));
160        Self {
161            classes,
162            methods,
163            global_order,
164            guarded_globals,
165        }
166    }
167
168    fn class(&self, name: &str) -> Result<&'a Class, CompileError> {
169        self.classes
170            .get(name)
171            .copied()
172            .ok_or_else(|| CompileError::plain(format!("unknown class `{name}` in Bash IR")))
173    }
174
175    fn field(&self, class: &str, field: &str) -> Result<&'a Field, CompileError> {
176        self.class(class)?
177            .fields
178            .iter()
179            .find(|candidate| candidate.name == field)
180            .ok_or_else(|| {
181                CompileError::plain(format!("unknown field `{class}.{field}` in Bash IR"))
182            })
183    }
184
185    fn is_static(&self, class: &str, method: &str) -> Result<bool, CompileError> {
186        self.methods.get(&(class, method)).copied().ok_or_else(|| {
187            CompileError::plain(format!("unknown method `{class}.{method}` in Bash IR"))
188        })
189    }
190}
191
192fn collect_statement_variables(statements: &[Stmt], names: &mut HashSet<String>) {
193    for statement in statements {
194        match statement {
195            Stmt::Let { value, .. } | Stmt::Expr(value) | Stmt::Return(Some(value)) => {
196                collect_expression_variables(value, names);
197            }
198            Stmt::Assign { place, value } => {
199                match place {
200                    Place::Variable(name) => {
201                        names.insert(name.clone());
202                    }
203                    Place::Field { object, .. } => collect_expression_variables(object, names),
204                }
205                collect_expression_variables(value, names);
206            }
207            Stmt::If {
208                condition,
209                then_body,
210                else_body,
211            } => {
212                collect_expression_variables(condition, names);
213                collect_statement_variables(then_body, names);
214                collect_statement_variables(else_body, names);
215            }
216            Stmt::While { condition, body } => {
217                collect_expression_variables(condition, names);
218                collect_statement_variables(body, names);
219            }
220            Stmt::For {
221                init,
222                condition,
223                update,
224                body,
225            } => {
226                collect_statement_variables(init, names);
227                if let Some(condition) = condition {
228                    collect_expression_variables(condition, names);
229                }
230                collect_statement_variables(update, names);
231                collect_statement_variables(body, names);
232            }
233            Stmt::Command { args, .. } => {
234                for argument in args {
235                    collect_expression_variables(argument, names);
236                }
237            }
238            Stmt::Block(body) => collect_statement_variables(body, names),
239            Stmt::Return(None) | Stmt::Break | Stmt::Continue | Stmt::Raw(_) | Stmt::Comment(_) => {
240            }
241        }
242    }
243}
244
245fn collect_expression_variables(expression: &Expr, names: &mut HashSet<String>) {
246    match &expression.kind {
247        ExprKind::Variable(name) => {
248            names.insert(name.clone());
249        }
250        ExprKind::Template(parts) => {
251            for part in parts {
252                collect_expression_variables(part, names);
253            }
254        }
255        ExprKind::Binary { left, right, .. } => {
256            collect_expression_variables(left, names);
257            collect_expression_variables(right, names);
258        }
259        ExprKind::Unary { value, .. } | ExprKind::Env(value) => {
260            collect_expression_variables(value, names);
261        }
262        ExprKind::Call { args, .. } | ExprKind::New { args, .. } => {
263            for argument in args {
264                collect_expression_variables(argument, names);
265            }
266        }
267        ExprKind::Field { object, .. } => collect_expression_variables(object, names),
268        ExprKind::Method { object, args, .. } => {
269            if let Some(object) = object {
270                collect_expression_variables(object, names);
271            }
272            for argument in args {
273                collect_expression_variables(argument, names);
274            }
275        }
276        ExprKind::String(_) | ExprKind::Number(_) | ExprKind::Boolean(_) => {}
277    }
278}
279
280#[derive(Debug, Clone)]
281enum ReturnMode {
282    TopLevel,
283    Function(Type),
284    Constructor,
285}
286
287#[derive(Debug, Clone)]
288enum LoopMode {
289    While,
290    For(Vec<Stmt>),
291}
292
293struct Writer<'a, 'n> {
294    code: String,
295    indent: usize,
296    metadata: &'a Metadata<'a>,
297    next_temp: &'n mut usize,
298    temps: Vec<String>,
299    loops: Vec<LoopMode>,
300    return_mode: ReturnMode,
301}
302
303impl<'a, 'n> Writer<'a, 'n> {
304    fn new(metadata: &'a Metadata<'a>, next_temp: &'n mut usize, return_mode: ReturnMode) -> Self {
305        Self {
306            code: String::new(),
307            indent: 0,
308            metadata,
309            next_temp,
310            temps: Vec::new(),
311            loops: Vec::new(),
312            return_mode,
313        }
314    }
315
316    fn line(&mut self, line: &str) {
317        for _ in 0..self.indent {
318            self.code.push_str("  ");
319        }
320        self.code.push_str(line);
321        self.code.push('\n');
322    }
323
324    fn fresh_temp(&mut self) -> String {
325        let name = format!("__tsh_backend_tmp_{}", *self.next_temp);
326        *self.next_temp += 1;
327        self.temps.push(name.clone());
328        name
329    }
330
331    fn emit_statements(&mut self, statements: &[Stmt]) -> Result<(), CompileError> {
332        for statement in statements {
333            self.emit_statement(statement)?;
334        }
335        Ok(())
336    }
337
338    fn emit_statement(&mut self, statement: &Stmt) -> Result<(), CompileError> {
339        match statement {
340            Stmt::Let { name, value } => {
341                let value = self.emit_expr(value)?;
342                self.line(&format!("{name}={}", value.word));
343                if matches!(&self.return_mode, ReturnMode::TopLevel)
344                    && self.metadata.guarded_globals.contains(name.as_str())
345                {
346                    self.line(&format!("{}=1", ready_flag(name)));
347                }
348            }
349            Stmt::Assign { place, value } => self.emit_assignment(place, value)?,
350            Stmt::Expr(expression) => {
351                let _ = self.emit_expr(expression)?;
352            }
353            Stmt::If {
354                condition,
355                then_body,
356                else_body,
357            } => {
358                let condition = self.emit_expr(condition)?;
359                self.line(&format!("if (( {} != 0 )); then", condition.arithmetic()?));
360                self.indent += 1;
361                self.emit_control_body(then_body)?;
362                self.indent -= 1;
363                if else_body.is_empty() {
364                    self.line("fi");
365                } else {
366                    self.line("else");
367                    self.indent += 1;
368                    self.emit_control_body(else_body)?;
369                    self.indent -= 1;
370                    self.line("fi");
371                }
372            }
373            Stmt::While { condition, body } => {
374                self.line("while :; do");
375                self.indent += 1;
376                let condition = self.emit_expr(condition)?;
377                self.line(&format!(
378                    "if (( {} == 0 )); then break; fi",
379                    condition.arithmetic()?
380                ));
381                self.loops.push(LoopMode::While);
382                self.emit_control_body(body)?;
383                self.loops.pop();
384                self.indent -= 1;
385                self.line("done");
386            }
387            Stmt::For {
388                init,
389                condition,
390                update,
391                body,
392            } => {
393                self.emit_statements(init)?;
394                self.line("while :; do");
395                self.indent += 1;
396                if let Some(condition) = condition {
397                    let condition = self.emit_expr(condition)?;
398                    self.line(&format!(
399                        "if (( {} == 0 )); then break; fi",
400                        condition.arithmetic()?
401                    ));
402                }
403                self.loops.push(LoopMode::For(update.clone()));
404                self.emit_control_body(body)?;
405                self.loops.pop();
406                self.emit_statements(update)?;
407                self.indent -= 1;
408                self.line("done");
409            }
410            Stmt::Return(value) => self.emit_return(value.as_ref())?,
411            Stmt::Break => {
412                if self.loops.is_empty() {
413                    return Err(CompileError::plain(
414                        "`break` is not inside a loop in Bash IR",
415                    ));
416                }
417                self.line("break");
418            }
419            Stmt::Continue => {
420                let mode = self.loops.last().cloned().ok_or_else(|| {
421                    CompileError::plain("`continue` is not inside a loop in Bash IR")
422                })?;
423                if let LoopMode::For(update) = mode {
424                    // Bash's continue jumps straight to the loop condition.
425                    // Emit the for-update here so its behavior matches the IR.
426                    self.emit_statements(&update)?;
427                }
428                self.line("continue");
429            }
430            Stmt::Command {
431                kind,
432                args,
433                recursive,
434            } => self.emit_command(*kind, args, *recursive)?,
435            Stmt::Raw(raw) => {
436                self.code.push_str(raw);
437                if !raw.ends_with('\n') {
438                    self.code.push('\n');
439                }
440            }
441            Stmt::Comment(comment) => self.emit_comment(comment),
442            Stmt::Block(body) => self.emit_statements(body)?,
443        }
444        Ok(())
445    }
446
447    fn emit_comment(&mut self, comment: &str) {
448        let lines = crate::backends::shell_comment_lines(comment);
449        if lines.is_empty() {
450            self.line("#");
451            return;
452        }
453        for text in lines {
454            self.line(&format!("# {text}"));
455        }
456    }
457
458    fn emit_control_body(&mut self, statements: &[Stmt]) -> Result<(), CompileError> {
459        let start = self.code.len();
460        self.emit_statements(statements)?;
461        let body = &self.code[start..];
462        let has_command = body.lines().any(|line| {
463            let line = line.trim();
464            !line.is_empty() && !line.starts_with('#')
465        });
466        if !has_command {
467            self.line(":");
468        }
469        Ok(())
470    }
471
472    fn emit_global_ready_check(&mut self, name: &str) {
473        let flag = ready_flag(name);
474        self.line(&format!("if (( {flag} == 0 )); then"));
475        self.indent += 1;
476        self.line(&format!(
477            "printf '%s\\n' {} >&2",
478            bash_quote(&format!(
479                "tsh: global `{name}` accessed before initialization"
480            ))
481        ));
482        self.line("exit 1");
483        self.indent -= 1;
484        self.line("fi");
485    }
486
487    fn emit_assignment(&mut self, place: &Place, expression: &Expr) -> Result<(), CompileError> {
488        match place {
489            Place::Variable(name) => {
490                if self.metadata.guarded_globals.contains(name.as_str())
491                    && !matches!(&self.return_mode, ReturnMode::TopLevel)
492                {
493                    self.emit_global_ready_check(name);
494                }
495                let value = self.emit_expr(expression)?;
496                self.line(&format!("{name}={}", value.word));
497            }
498            Place::Field {
499                object,
500                class,
501                field,
502            } => {
503                self.metadata.field(class, field)?;
504                let object_value = self.emit_expr(object)?;
505                let object = self.capture_if_variable(object, object_value);
506                let value = self.emit_expr(expression)?;
507                self.line(&format!(
508                    "{}[${}]={}",
509                    field_array(class, field),
510                    object.arithmetic()?,
511                    value.word
512                ));
513            }
514        }
515        Ok(())
516    }
517
518    fn emit_return(&mut self, expression: Option<&Expr>) -> Result<(), CompileError> {
519        match self.return_mode.clone() {
520            ReturnMode::TopLevel => Err(CompileError::plain(
521                "`return` is not valid at top level in Bash IR",
522            )),
523            ReturnMode::Constructor => {
524                if let Some(expression) = expression {
525                    if !matches!(expression.ty, Type::Void) {
526                        return Err(CompileError::plain(
527                            "a constructor cannot return a value in Bash IR",
528                        ));
529                    }
530                    let _ = self.emit_expr(expression)?;
531                }
532                self.line("__tsh_backend_result=\"${__tsh_this}\"");
533                self.line("return 0");
534                Ok(())
535            }
536            ReturnMode::Function(return_type) => {
537                if let Some(expression) = expression {
538                    let value = self.emit_expr(expression)?;
539                    self.line(&format!("__tsh_backend_result={}", value.word));
540                } else if matches!(return_type, Type::Void) {
541                    self.line("__tsh_backend_result=''");
542                } else {
543                    return Err(CompileError::plain(
544                        "non-void function returned without a value in Bash IR",
545                    ));
546                }
547                self.line("return 0");
548                Ok(())
549            }
550        }
551    }
552
553    fn emit_expr(&mut self, expression: &Expr) -> Result<Value, CompileError> {
554        match &expression.kind {
555            ExprKind::String(value) => {
556                Ok(Value::new(bash_quote(value), None, expression.ty.clone()))
557            }
558            ExprKind::Number(value) => Ok(Value::new(
559                value.to_string(),
560                Some(value.to_string()),
561                expression.ty.clone(),
562            )),
563            ExprKind::Boolean(value) => {
564                let bit = if *value { "1" } else { "0" };
565                Ok(Value::new(bit, Some(bit.to_owned()), expression.ty.clone()))
566            }
567            ExprKind::Variable(name) => {
568                if self.metadata.guarded_globals.contains(name.as_str())
569                    && !matches!(&self.return_mode, ReturnMode::TopLevel)
570                {
571                    self.emit_global_ready_check(name);
572                }
573                let arithmetic = is_arithmetic_type(&expression.ty).then(|| name.clone());
574                Ok(
575                    Value::new(shell_expansion(name), arithmetic, expression.ty.clone())
576                        .named(name),
577                )
578            }
579            ExprKind::Template(parts) => self.emit_template(parts, expression.ty.clone()),
580            ExprKind::Binary { op, left, right } => {
581                self.emit_binary(op, left, right, expression.ty.clone())
582            }
583            ExprKind::Unary { op, value } => self.emit_unary(op, value, expression.ty.clone()),
584            ExprKind::Call { function, args } => {
585                self.emit_call(function, args, expression.ty.clone())
586            }
587            ExprKind::New { class, args } => self.emit_new(class, args),
588            ExprKind::Field {
589                object,
590                class,
591                field,
592            } => {
593                self.metadata.field(class, field)?;
594                let object_value = self.emit_expr(object)?;
595                let object = self.capture_if_variable(object, object_value);
596                let temp = self.fresh_temp();
597                self.line(&format!(
598                    "{temp}=\"${{{}[${}]}}\"",
599                    field_array(class, field),
600                    object.arithmetic()?
601                ));
602                let arithmetic = is_arithmetic_type(&expression.ty).then(|| temp.clone());
603                Ok(
604                    Value::new(shell_expansion(&temp), arithmetic, expression.ty.clone())
605                        .named(temp),
606                )
607            }
608            ExprKind::Method {
609                object,
610                class,
611                method,
612                args,
613            } => self.emit_method_call(
614                object.as_deref(),
615                class,
616                method,
617                args,
618                expression.ty.clone(),
619            ),
620            ExprKind::Env(key) => self.emit_env(key, expression.ty.clone()),
621        }
622    }
623
624    fn emit_template(&mut self, parts: &[Expr], result_type: Type) -> Result<Value, CompileError> {
625        let result = self.fresh_temp();
626        self.line(&format!("{result}=''"));
627        for part in parts {
628            if matches!(part.ty, Type::Void) {
629                return Err(CompileError::plain(
630                    "cannot interpolate a void expression in Bash IR",
631                ));
632            }
633            let mut value = self.emit_expr(part)?;
634            if matches!(value.ty, Type::Boolean) {
635                value = self.boolean_as_text(value)?;
636            }
637            self.line(&format!("{result}=\"${{{result}}}\"{}", value.word));
638        }
639        Ok(Value::new(shell_expansion(&result), None, result_type))
640    }
641
642    fn emit_binary(
643        &mut self,
644        op: &str,
645        left: &Expr,
646        right: &Expr,
647        result_type: Type,
648    ) -> Result<Value, CompileError> {
649        if op == "&&" || op == "||" {
650            return self.emit_logical(op, left, right, result_type);
651        }
652
653        let left_value = self.emit_expr(left)?;
654        let mut left = self.capture_if_variable(left, left_value);
655        if op == "+" && matches!(result_type, Type::String) && matches!(left.ty, Type::Boolean) {
656            left = self.boolean_as_text(left)?;
657        }
658        let right_value = self.emit_expr(right)?;
659        let mut right = self.capture_if_variable(right, right_value);
660        if op == "+" && matches!(result_type, Type::String) && matches!(right.ty, Type::Boolean) {
661            right = self.boolean_as_text(right)?;
662        }
663        let result = self.fresh_temp();
664
665        if op == "+" && matches!(result_type, Type::String) {
666            self.line(&format!("{result}={}{}", left.word, right.word));
667            return Ok(Value::new(shell_expansion(&result), None, result_type));
668        }
669
670        if is_comparison(op) {
671            let condition = if is_numeric_type(&left.ty) && is_numeric_type(&right.ty) {
672                format!(
673                    "(( {} {} {} ))",
674                    left.arithmetic()?,
675                    normalize_comparison(op)?,
676                    right.arithmetic()?
677                )
678            } else {
679                let a = &left.word;
680                let b = &right.word;
681                match normalize_comparison(op)? {
682                    "==" => format!("[[ {a} == {b} ]]"),
683                    "!=" => format!("[[ {a} != {b} ]]"),
684                    "<" => format!("[[ {a} < {b} ]]"),
685                    ">" => format!("[[ {a} > {b} ]]"),
686                    "<=" => format!("[[ {a} < {b} || {a} == {b} ]]"),
687                    ">=" => format!("[[ {a} > {b} || {a} == {b} ]]"),
688                    _ => unreachable!(),
689                }
690            };
691            self.emit_boolean_assignment(&result, &condition);
692            return Ok(Value::new(
693                shell_expansion(&result),
694                Some(result.clone()),
695                result_type,
696            ));
697        }
698
699        let arithmetic_op = match op {
700            "+" | "-" | "*" | "/" | "%" => op,
701            _ => {
702                return Err(CompileError::plain(format!(
703                    "unsupported Bash binary operator `{op}`"
704                )));
705            }
706        };
707        self.line(&format!(
708            "{result}=$(( {} {arithmetic_op} {} ))",
709            left.arithmetic()?,
710            right.arithmetic()?
711        ));
712        let arithmetic = is_arithmetic_type(&result_type).then(|| result.clone());
713        Ok(Value::new(
714            shell_expansion(&result),
715            arithmetic,
716            result_type,
717        ))
718    }
719
720    fn emit_logical(
721        &mut self,
722        op: &str,
723        left: &Expr,
724        right: &Expr,
725        result_type: Type,
726    ) -> Result<Value, CompileError> {
727        if !matches!(result_type, Type::Boolean) {
728            return Err(CompileError::plain(
729                "logical Bash IR expression must have boolean type",
730            ));
731        }
732        let left = self.emit_expr(left)?;
733        let result = self.fresh_temp();
734        self.line(&format!("{result}=0"));
735        match op {
736            "&&" => {
737                self.line(&format!("if (( {} != 0 )); then", left.arithmetic()?));
738                self.indent += 1;
739                let right = self.emit_expr(right)?;
740                self.line(&format!("{result}={}", right.word));
741                self.indent -= 1;
742                self.line("fi");
743            }
744            "||" => {
745                self.line(&format!("if (( {} == 0 )); then", left.arithmetic()?));
746                self.indent += 1;
747                let right = self.emit_expr(right)?;
748                self.line(&format!("{result}={}", right.word));
749                self.indent -= 1;
750                self.line("else");
751                self.indent += 1;
752                self.line(&format!("{result}=1"));
753                self.indent -= 1;
754                self.line("fi");
755            }
756            _ => unreachable!(),
757        }
758        Ok(Value::new(
759            shell_expansion(&result),
760            Some(result.clone()),
761            result_type,
762        ))
763    }
764
765    fn emit_unary(
766        &mut self,
767        op: &str,
768        expression: &Expr,
769        result_type: Type,
770    ) -> Result<Value, CompileError> {
771        let value = self.emit_expr(expression)?;
772        let value = self.capture_if_variable(expression, value);
773        let result = self.fresh_temp();
774        match op {
775            "!" => {
776                self.line(&format!("if (( {} == 0 )); then", value.arithmetic()?));
777                self.indent += 1;
778                self.line(&format!("{result}=1"));
779                self.indent -= 1;
780                self.line("else");
781                self.indent += 1;
782                self.line(&format!("{result}=0"));
783                self.indent -= 1;
784                self.line("fi");
785                Ok(Value::new(
786                    shell_expansion(&result),
787                    Some(result),
788                    result_type,
789                ))
790            }
791            "-" => {
792                self.line(&format!("{result}=$(( -{} ))", value.arithmetic()?));
793                let arithmetic = is_arithmetic_type(&result_type).then(|| result.clone());
794                Ok(Value::new(
795                    shell_expansion(&result),
796                    arithmetic,
797                    result_type,
798                ))
799            }
800            "+" => {
801                self.line(&format!("{result}=$(( {} ))", value.arithmetic()?));
802                Ok(Value::new(
803                    shell_expansion(&result),
804                    Some(result),
805                    result_type,
806                ))
807            }
808            _ => Err(CompileError::plain(format!(
809                "unsupported Bash unary operator `{op}`"
810            ))),
811        }
812    }
813
814    fn emit_call(
815        &mut self,
816        function: &str,
817        args: &[Expr],
818        result_type: Type,
819    ) -> Result<Value, CompileError> {
820        let args = self.capture_arguments(args)?;
821        let call = command_words(&format!("__tsh_fn_{function}"), &args);
822        self.line(&call);
823        let result = self.capture_result(result_type);
824        Ok(result)
825    }
826
827    fn emit_new(&mut self, class: &str, args: &[Expr]) -> Result<Value, CompileError> {
828        self.metadata.class(class)?;
829        let args = self.capture_arguments(args)?;
830        let call = command_words(&format!("__tsh_class_{class}"), &args);
831        self.line(&call);
832        Ok(self.capture_result(Type::Class(class.to_owned())))
833    }
834
835    fn emit_method_call(
836        &mut self,
837        object: Option<&Expr>,
838        class: &str,
839        method: &str,
840        args: &[Expr],
841        result_type: Type,
842    ) -> Result<Value, CompileError> {
843        let is_static = self.metadata.is_static(class, method)?;
844        let object = match (object, is_static) {
845            (Some(object), false) => {
846                let object_value = self.emit_expr(object)?;
847                Some(self.capture_if_variable(object, object_value))
848            }
849            (None, false) => {
850                return Err(CompileError::plain(format!(
851                    "instance method `{class}.{method}` has no receiver in Bash IR"
852                )));
853            }
854            (Some(_), true) => {
855                return Err(CompileError::plain(format!(
856                    "static method `{class}.{method}` unexpectedly has a receiver in Bash IR"
857                )));
858            }
859            (None, true) => None,
860        };
861        let args = self.capture_arguments(args)?;
862        let mut call = format!("__tsh_classMethod_{class}_{method}");
863        if let Some(object) = object {
864            call.push(' ');
865            call.push_str(&object.word);
866        }
867        for argument in &args {
868            call.push(' ');
869            call.push_str(&argument.word);
870        }
871        self.line(&call);
872        Ok(self.capture_result(result_type))
873    }
874
875    fn emit_env(&mut self, expression: &Expr, result_type: Type) -> Result<Value, CompileError> {
876        let key = self.emit_expr(expression)?;
877        let key = self.capture(key);
878        let result = self.fresh_temp();
879        self.line(&format!("{result}=''"));
880        let key_name = key.name.as_deref().ok_or_else(|| {
881            CompileError::plain("Bash environment key was not captured into a variable")
882        })?;
883        // Bash indirection is safe here because the key is validated first;
884        // no user-controlled text is passed through eval.
885        self.line(&format!(
886            "if [[ {} =~ ^[a-zA-Z_][a-zA-Z0-9_]*$ ]]; then",
887            key.word
888        ));
889        self.indent += 1;
890        self.line(&format!("{result}=\"${{!{key_name}}}\""));
891        self.indent -= 1;
892        self.line("fi");
893        Ok(Value::new(shell_expansion(&result), None, result_type).named(result))
894    }
895
896    fn emit_command(
897        &mut self,
898        kind: Command,
899        args: &[Expr],
900        recursive: bool,
901    ) -> Result<(), CompileError> {
902        match kind {
903            Command::Exit => {
904                if args.len() > 1 {
905                    return Err(CompileError::plain(
906                        "`exit` accepts at most one argument in Bash IR",
907                    ));
908                }
909                if let Some(value) = args.first() {
910                    let value = self.emit_expr(value)?;
911                    let value = self.capture(value);
912                    self.line(&format!("exit {}", value.word));
913                } else {
914                    self.line("exit 0");
915                }
916            }
917            Command::Echo => {
918                let values = self.capture_arguments(args)?;
919                let mut format = String::new();
920                let mut words = Vec::new();
921                for (index, value) in values.iter().enumerate() {
922                    if index > 0 {
923                        format.push(' ');
924                    }
925                    format.push_str("%s");
926                    let value = if matches!(value.ty, Type::Boolean) {
927                        self.boolean_as_text(value.clone())?
928                    } else {
929                        value.clone()
930                    };
931                    words.push(value.word);
932                }
933                let command = if words.is_empty() {
934                    format!("printf {}", bash_quote("\\n"))
935                } else {
936                    format.push_str("\\n");
937                    let mut command = format!("printf {}", bash_quote(&format));
938                    for word in words {
939                        command.push(' ');
940                        command.push_str(&word);
941                    }
942                    command
943                };
944                self.emit_checked_command(&command);
945            }
946            Command::Mkdir
947            | Command::Rm
948            | Command::Cp
949            | Command::Mv
950            | Command::Cd
951            | Command::Run => {
952                if kind == Command::Run && args.is_empty() {
953                    return Err(CompileError::plain("`run` needs a command in Bash IR"));
954                }
955                let values = self.capture_arguments(args)?;
956                let mut command = match kind {
957                    Command::Mkdir => if recursive { "mkdir -p --" } else { "mkdir --" }.to_owned(),
958                    Command::Rm => if recursive { "rm -r --" } else { "rm --" }.to_owned(),
959                    Command::Cp => "cp --".to_owned(),
960                    Command::Mv => "mv --".to_owned(),
961                    Command::Cd => "cd --".to_owned(),
962                    Command::Run => String::new(),
963                    _ => unreachable!(),
964                };
965                for value in values {
966                    let value = if matches!(value.ty, Type::Boolean) {
967                        self.boolean_as_text(value)?
968                    } else {
969                        value
970                    };
971                    if !command.is_empty() {
972                        command.push(' ');
973                    }
974                    command.push_str(&value.word);
975                }
976                self.emit_checked_command(&command);
977            }
978            Command::Chmod => {
979                if args.len() != 2 {
980                    return Err(CompileError::plain(
981                        "`chmod` expects path and mode arguments in Bash IR",
982                    ));
983                }
984                // Source order is chmod(path, mode), but the shell command is
985                // chmod mode path. Capture both before the conversion.
986                let path_value = self.emit_expr(&args[0])?;
987                let path = self.capture_if_variable(&args[0], path_value);
988                let mode_value = self.emit_expr(&args[1])?;
989                let mode = self.capture_if_variable(&args[1], mode_value);
990                let octal = self.fresh_temp();
991                if let ExprKind::Number(decimal) = &args[1].kind {
992                    if *decimal < 0 {
993                        return Err(CompileError::plain(
994                            "chmod mode cannot be negative in Bash IR",
995                        ));
996                    }
997                    self.line(&format!("{octal}={}", bash_quote(&format!("{decimal:o}"))));
998                } else if matches!(mode.ty, Type::String) {
999                    // String modes already use chmod's textual syntax, such
1000                    // as `755`, `u+x`, or `a-w`.
1001                    self.line(&format!("{octal}={}", mode.word));
1002                } else {
1003                    self.line(&format!(
1004                        "printf -v {octal} '%o' \"${{{}}}\"",
1005                        mode.arithmetic()?
1006                    ));
1007                }
1008                let recursive_flag = if recursive { " -R" } else { "" };
1009                self.emit_checked_command(&format!(
1010                    "chmod{recursive_flag} -- \"${{{octal}}}\" {}",
1011                    path.word
1012                ));
1013            }
1014        }
1015        Ok(())
1016    }
1017
1018    fn emit_checked_command(&mut self, command: &str) {
1019        // The right-hand side sees the exact status of the failed command.
1020        self.line(&format!("{command} || exit $?"));
1021    }
1022
1023    fn emit_boolean_assignment(&mut self, destination: &str, condition: &str) {
1024        self.line(&format!("if {condition}; then"));
1025        self.indent += 1;
1026        self.line(&format!("{destination}=1"));
1027        self.indent -= 1;
1028        self.line("else");
1029        self.indent += 1;
1030        self.line(&format!("{destination}=0"));
1031        self.indent -= 1;
1032        self.line("fi");
1033    }
1034
1035    fn capture_arguments(&mut self, args: &[Expr]) -> Result<Vec<Value>, CompileError> {
1036        let mut values = Vec::with_capacity(args.len());
1037        for argument in args {
1038            let value = self.emit_expr(argument)?;
1039            values.push(self.capture_if_variable(argument, value));
1040        }
1041        Ok(values)
1042    }
1043
1044    fn capture_if_variable(&mut self, expression: &Expr, value: Value) -> Value {
1045        if matches!(expression.kind, ExprKind::Variable(_)) {
1046            self.capture(value)
1047        } else {
1048            value
1049        }
1050    }
1051
1052    fn capture(&mut self, value: Value) -> Value {
1053        let temp = self.fresh_temp();
1054        self.line(&format!("{temp}={}", value.word));
1055        let arithmetic = is_arithmetic_type(&value.ty).then(|| temp.clone());
1056        Value::new(shell_expansion(&temp), arithmetic, value.ty).named(temp)
1057    }
1058
1059    fn capture_result(&mut self, ty: Type) -> Value {
1060        let temp = self.fresh_temp();
1061        self.line(&format!("{temp}=\"${{__tsh_backend_result}}\""));
1062        let arithmetic = is_arithmetic_type(&ty).then(|| temp.clone());
1063        Value::new(shell_expansion(&temp), arithmetic, ty).named(temp)
1064    }
1065
1066    fn boolean_as_text(&mut self, value: Value) -> Result<Value, CompileError> {
1067        if !matches!(value.ty, Type::Boolean) {
1068            return Ok(value);
1069        }
1070        if value.name.is_none() {
1071            if value.arithmetic.as_deref() == Some("1") {
1072                return Ok(Value::new(bash_quote("true"), None, Type::String));
1073            }
1074            if value.arithmetic.as_deref() == Some("0") {
1075                return Ok(Value::new(bash_quote("false"), None, Type::String));
1076            }
1077        }
1078        let source = if value.arithmetic.is_some() {
1079            value
1080        } else {
1081            self.capture(value)
1082        };
1083        let result = self.fresh_temp();
1084        self.line(&format!("if (( {} != 0 )); then", source.arithmetic()?));
1085        self.indent += 1;
1086        self.line(&format!("{result}='true'"));
1087        self.indent -= 1;
1088        self.line("else");
1089        self.indent += 1;
1090        self.line(&format!("{result}='false'"));
1091        self.indent -= 1;
1092        self.line("fi");
1093        Ok(Value::new(shell_expansion(&result), None, Type::String))
1094    }
1095}
1096
1097fn emit_function(
1098    function: &Function,
1099    method: Option<(&Class, bool)>,
1100    metadata: &Metadata<'_>,
1101    next_temp: &mut usize,
1102) -> Result<String, CompileError> {
1103    let mut writer = Writer::new(
1104        metadata,
1105        next_temp,
1106        ReturnMode::Function(function.return_type.clone()),
1107    );
1108    writer.indent = 1;
1109    writer.emit_statements(&function.body)?;
1110    writer.line(&format!(
1111        "__tsh_backend_result={}",
1112        default_value(&function.return_type)
1113    ));
1114
1115    let mut locals = Vec::new();
1116    if let Some((_, true)) = method {
1117        locals.push("__tsh_this".to_owned());
1118    }
1119    locals.extend(function.params.iter().map(|param| param.name.clone()));
1120    collect_let_names(&function.body, &mut locals);
1121    locals.extend(writer.temps.iter().cloned());
1122    deduplicate(&mut locals);
1123
1124    let mut output = String::new();
1125    let symbol = match method {
1126        Some((class, _)) => format!("__tsh_classMethod_{}_{}", class.name, function.name),
1127        None => format!("__tsh_fn_{}", function.name),
1128    };
1129    output.push_str(&format!("{symbol}() {{\n"));
1130    for chunk in locals.chunks(20) {
1131        output.push_str("  local");
1132        for name in chunk {
1133            output.push(' ');
1134            output.push_str(name);
1135        }
1136        output.push('\n');
1137    }
1138    let mut index = 1usize;
1139    if let Some((_, true)) = method {
1140        output.push_str("  __tsh_this=\"$1\"\n");
1141        index += 1;
1142    }
1143    for param in &function.params {
1144        output.push_str(&format!("  {}=\"${index}\"\n", param.name));
1145        index += 1;
1146    }
1147    output.push_str(&writer.code);
1148    output.push_str("}\n");
1149    Ok(output)
1150}
1151
1152fn emit_constructor(
1153    class: &Class,
1154    metadata: &Metadata<'_>,
1155    next_temp: &mut usize,
1156) -> Result<String, CompileError> {
1157    let mut writer = Writer::new(metadata, next_temp, ReturnMode::Constructor);
1158    writer.indent = 1;
1159    // Allocate IDs from one shared counter, so identities are never reused or
1160    // ambiguous across classes.
1161    writer.line("__tsh_backend_next_object_id=$(( __tsh_backend_next_object_id + 1 ))");
1162    writer.line("__tsh_this=\"${__tsh_backend_next_object_id}\"");
1163    for field in &class.fields {
1164        let array = field_array(&class.name, &field.name);
1165        if let Some(initial) = &field.initial {
1166            let value = writer.emit_expr(initial)?;
1167            writer.line(&format!("{array}[$__tsh_this]={}", value.word));
1168        } else {
1169            writer.line(&format!(
1170                "{array}[$__tsh_this]={}",
1171                default_value(&field.ty)
1172            ));
1173        }
1174    }
1175    writer.emit_statements(&class.constructor.body)?;
1176    writer.line("__tsh_backend_result=\"${__tsh_this}\"");
1177
1178    let mut locals = vec!["__tsh_this".to_owned()];
1179    locals.extend(
1180        class
1181            .constructor
1182            .params
1183            .iter()
1184            .map(|param| param.name.clone()),
1185    );
1186    collect_let_names(&class.constructor.body, &mut locals);
1187    locals.extend(writer.temps.iter().cloned());
1188    deduplicate(&mut locals);
1189
1190    let mut output = format!("__tsh_class_{}() {{\n", class.name);
1191    for chunk in locals.chunks(20) {
1192        output.push_str("  local");
1193        for name in chunk {
1194            output.push(' ');
1195            output.push_str(name);
1196        }
1197        output.push('\n');
1198    }
1199    for (index, param) in class.constructor.params.iter().enumerate() {
1200        output.push_str(&format!("  {}=\"${}\"\n", param.name, index + 1));
1201    }
1202    output.push_str(&writer.code);
1203    output.push_str("}\n");
1204    Ok(output)
1205}
1206
1207fn emit_method(
1208    class: &Class,
1209    method: &Method,
1210    metadata: &Metadata<'_>,
1211    next_temp: &mut usize,
1212) -> Result<String, CompileError> {
1213    emit_function(
1214        &method.function,
1215        Some((class, !method.is_static)),
1216        metadata,
1217        next_temp,
1218    )
1219}
1220
1221fn collect_let_names(statements: &[Stmt], locals: &mut Vec<String>) {
1222    for statement in statements {
1223        match statement {
1224            Stmt::Let { name, .. } => locals.push(name.clone()),
1225            Stmt::If {
1226                then_body,
1227                else_body,
1228                ..
1229            } => {
1230                collect_let_names(then_body, locals);
1231                collect_let_names(else_body, locals);
1232            }
1233            Stmt::While { body, .. } | Stmt::Block(body) => collect_let_names(body, locals),
1234            Stmt::For {
1235                init, update, body, ..
1236            } => {
1237                collect_let_names(init, locals);
1238                collect_let_names(update, locals);
1239                collect_let_names(body, locals);
1240            }
1241            _ => {}
1242        }
1243    }
1244}
1245
1246fn deduplicate(values: &mut Vec<String>) {
1247    let mut seen = HashSet::new();
1248    values.retain(|value| seen.insert(value.clone()));
1249}
1250
1251fn command_words(command: &str, args: &[Value]) -> String {
1252    let mut output = command.to_owned();
1253    for arg in args {
1254        output.push(' ');
1255        output.push_str(&arg.word);
1256    }
1257    output
1258}
1259
1260fn shell_expansion(name: &str) -> String {
1261    format!("\"${{{name}}}\"")
1262}
1263
1264fn bash_quote(value: &str) -> String {
1265    if value.is_empty() {
1266        return "''".to_owned();
1267    }
1268    format!("'{}'", value.replace('\'', "'\\''"))
1269}
1270
1271fn field_array(class: &str, field: &str) -> String {
1272    format!(
1273        "__tsh_backend_field_{}_{}",
1274        encode_identifier_component(class),
1275        encode_identifier_component(field)
1276    )
1277}
1278
1279fn ready_flag(name: &str) -> String {
1280    format!("__tsh_backend_ready_{name}")
1281}
1282
1283fn encode_identifier_component(value: &str) -> String {
1284    value
1285        .as_bytes()
1286        .iter()
1287        .map(|byte| format!("{byte:02x}"))
1288        .collect()
1289}
1290
1291fn validate_program(program: &Program) -> Result<(), CompileError> {
1292    for function in &program.functions {
1293        validate_function(function)?;
1294    }
1295    for class in &program.classes {
1296        validate_identifier(&class.name)?;
1297        for field in &class.fields {
1298            if let Some(initial) = &field.initial {
1299                validate_expr(initial)?;
1300            }
1301        }
1302        validate_function(&class.constructor)?;
1303        for method in &class.methods {
1304            validate_function(&method.function)?;
1305        }
1306    }
1307    validate_statements(&program.body)
1308}
1309
1310fn validate_function(function: &Function) -> Result<(), CompileError> {
1311    validate_identifier(&function.name)?;
1312    for param in &function.params {
1313        validate_identifier(&param.name)?;
1314    }
1315    validate_statements(&function.body)
1316}
1317
1318fn validate_statements(statements: &[Stmt]) -> Result<(), CompileError> {
1319    for statement in statements {
1320        match statement {
1321            Stmt::Let { name, value } => {
1322                validate_identifier(name)?;
1323                validate_expr(value)?;
1324            }
1325            Stmt::Assign { place, value } => {
1326                match place {
1327                    Place::Variable(name) => validate_identifier(name)?,
1328                    Place::Field { object, class, .. } => {
1329                        validate_identifier(class)?;
1330                        validate_expr(object)?;
1331                    }
1332                }
1333                validate_expr(value)?;
1334            }
1335            Stmt::Expr(expression) | Stmt::Return(Some(expression)) => validate_expr(expression)?,
1336            Stmt::If {
1337                condition,
1338                then_body,
1339                else_body,
1340            } => {
1341                validate_expr(condition)?;
1342                validate_statements(then_body)?;
1343                validate_statements(else_body)?;
1344            }
1345            Stmt::While { condition, body } => {
1346                validate_expr(condition)?;
1347                validate_statements(body)?;
1348            }
1349            Stmt::For {
1350                init,
1351                condition,
1352                update,
1353                body,
1354            } => {
1355                validate_statements(init)?;
1356                if let Some(condition) = condition {
1357                    validate_expr(condition)?;
1358                }
1359                validate_statements(update)?;
1360                validate_statements(body)?;
1361            }
1362            Stmt::Command { args, .. } => {
1363                for argument in args {
1364                    validate_expr(argument)?;
1365                }
1366            }
1367            Stmt::Block(body) => validate_statements(body)?,
1368            Stmt::Return(None) | Stmt::Break | Stmt::Continue | Stmt::Raw(_) | Stmt::Comment(_) => {
1369            }
1370        }
1371    }
1372    Ok(())
1373}
1374
1375fn validate_expr(expression: &Expr) -> Result<(), CompileError> {
1376    match &expression.kind {
1377        ExprKind::String(_) | ExprKind::Number(_) | ExprKind::Boolean(_) => {}
1378        ExprKind::Variable(name) => validate_identifier(name)?,
1379        ExprKind::Template(parts) => {
1380            for part in parts {
1381                validate_expr(part)?;
1382            }
1383        }
1384        ExprKind::Binary { left, right, .. } => {
1385            validate_expr(left)?;
1386            validate_expr(right)?;
1387        }
1388        ExprKind::Unary { value, .. } | ExprKind::Env(value) => validate_expr(value)?,
1389        ExprKind::Call { function, args } => {
1390            validate_identifier(function)?;
1391            for argument in args {
1392                validate_expr(argument)?;
1393            }
1394        }
1395        ExprKind::New { class, args } => {
1396            validate_identifier(class)?;
1397            for argument in args {
1398                validate_expr(argument)?;
1399            }
1400        }
1401        ExprKind::Field { object, class, .. } => {
1402            validate_identifier(class)?;
1403            validate_expr(object)?;
1404        }
1405        ExprKind::Method {
1406            object,
1407            class,
1408            method,
1409            args,
1410        } => {
1411            validate_identifier(class)?;
1412            validate_identifier(method)?;
1413            if let Some(object) = object {
1414                validate_expr(object)?;
1415            }
1416            for argument in args {
1417                validate_expr(argument)?;
1418            }
1419        }
1420    }
1421    Ok(())
1422}
1423
1424fn validate_identifier(name: &str) -> Result<(), CompileError> {
1425    let mut bytes = name.bytes();
1426    let valid_start = bytes
1427        .next()
1428        .is_some_and(|byte| byte == b'_' || byte.is_ascii_alphabetic());
1429    if valid_start && bytes.all(|byte| byte == b'_' || byte.is_ascii_alphanumeric()) {
1430        Ok(())
1431    } else {
1432        Err(CompileError::plain(format!(
1433            "unsafe shell identifier `{name}` in Bash IR"
1434        )))
1435    }
1436}
1437
1438fn is_numeric_type(ty: &Type) -> bool {
1439    matches!(ty, Type::Number | Type::Boolean | Type::Class(_))
1440}
1441
1442fn is_arithmetic_type(ty: &Type) -> bool {
1443    is_numeric_type(ty)
1444}
1445
1446fn is_comparison(op: &str) -> bool {
1447    matches!(op, "==" | "===" | "!=" | "!==" | "<" | "<=" | ">" | ">=")
1448}
1449
1450fn normalize_comparison(op: &str) -> Result<&'static str, CompileError> {
1451    match op {
1452        "==" | "===" => Ok("=="),
1453        "!=" | "!==" => Ok("!="),
1454        "<" => Ok("<"),
1455        "<=" => Ok("<="),
1456        ">" => Ok(">"),
1457        ">=" => Ok(">="),
1458        _ => Err(CompileError::plain(format!(
1459            "unsupported Bash comparison operator `{op}`"
1460        ))),
1461    }
1462}
1463
1464fn default_value(ty: &Type) -> &'static str {
1465    match ty {
1466        Type::Number | Type::Boolean | Type::Class(_) => "0",
1467        Type::String | Type::Void => "''",
1468    }
1469}
1470
1471#[cfg(test)]
1472mod tests {
1473    use std::process::{Command as ProcessCommand, Output};
1474
1475    use super::*;
1476
1477    fn expr(kind: ExprKind, ty: Type) -> Expr {
1478        Expr { kind, ty }
1479    }
1480
1481    fn number(value: i64) -> Expr {
1482        expr(ExprKind::Number(value), Type::Number)
1483    }
1484
1485    fn boolean(value: bool) -> Expr {
1486        expr(ExprKind::Boolean(value), Type::Boolean)
1487    }
1488
1489    fn string(value: &str) -> Expr {
1490        expr(ExprKind::String(value.to_owned()), Type::String)
1491    }
1492
1493    fn variable(name: &str, ty: Type) -> Expr {
1494        expr(ExprKind::Variable(name.to_owned()), ty)
1495    }
1496
1497    fn command(kind: Command, args: Vec<Expr>, recursive: bool) -> Stmt {
1498        Stmt::Command {
1499            kind,
1500            args,
1501            recursive,
1502        }
1503    }
1504
1505    fn run_bash(script: &str, cwd: Option<&std::path::Path>) -> Output {
1506        let mut command = ProcessCommand::new("bash");
1507        command.args(["--noprofile", "--norc", "-c", script]);
1508        if let Some(cwd) = cwd {
1509            command.current_dir(cwd);
1510        }
1511        command
1512            .output()
1513            .expect("Bash is required to run backend tests")
1514    }
1515
1516    fn factorial_program() -> Program {
1517        let n = variable("n", Type::Number);
1518        let base_condition = expr(
1519            ExprKind::Binary {
1520                op: "<=".to_owned(),
1521                left: Box::new(n.clone()),
1522                right: Box::new(number(1)),
1523            },
1524            Type::Boolean,
1525        );
1526        let recursive_argument = expr(
1527            ExprKind::Binary {
1528                op: "-".to_owned(),
1529                left: Box::new(n.clone()),
1530                right: Box::new(number(1)),
1531            },
1532            Type::Number,
1533        );
1534        let recursive_call = expr(
1535            ExprKind::Call {
1536                function: "fact".to_owned(),
1537                args: vec![recursive_argument],
1538            },
1539            Type::Number,
1540        );
1541        let recursive_result = expr(
1542            ExprKind::Binary {
1543                op: "*".to_owned(),
1544                left: Box::new(n),
1545                right: Box::new(recursive_call),
1546            },
1547            Type::Number,
1548        );
1549        Program {
1550            functions: vec![Function {
1551                name: "fact".to_owned(),
1552                params: vec![crate::ir::Param {
1553                    name: "n".to_owned(),
1554                    ty: Type::Number,
1555                }],
1556                return_type: Type::Number,
1557                body: vec![Stmt::If {
1558                    condition: base_condition,
1559                    then_body: vec![Stmt::Return(Some(number(1)))],
1560                    else_body: vec![Stmt::Return(Some(recursive_result))],
1561                }],
1562            }],
1563            body: vec![command(
1564                Command::Echo,
1565                vec![expr(
1566                    ExprKind::Call {
1567                        function: "fact".to_owned(),
1568                        args: vec![number(6)],
1569                    },
1570                    Type::Number,
1571                )],
1572                false,
1573            )],
1574            ..Program::default()
1575        }
1576    }
1577
1578    #[test]
1579    fn recursive_calls_keep_each_frames_temporaries_and_result() {
1580        let script = Bash.emit(&factorial_program()).expect("emit factorial");
1581        assert!(script.contains("__tsh_fn_fact"));
1582        let output = run_bash(&script, None);
1583        assert!(
1584            output.status.success(),
1585            "{}",
1586            String::from_utf8_lossy(&output.stderr)
1587        );
1588        assert_eq!(String::from_utf8_lossy(&output.stdout), "720\n");
1589    }
1590
1591    #[test]
1592    fn global_initialization_guards_allow_ready_globals_and_reject_tdz_calls() {
1593        let read_first = Function {
1594            name: "read_first".to_owned(),
1595            params: vec![],
1596            return_type: Type::Number,
1597            body: vec![Stmt::Return(Some(variable("first", Type::Number)))],
1598        };
1599        let safe = Program {
1600            functions: vec![read_first.clone()],
1601            body: vec![
1602                Stmt::Let {
1603                    name: "first".to_owned(),
1604                    value: number(41),
1605                },
1606                Stmt::Let {
1607                    name: "answer".to_owned(),
1608                    value: expr(
1609                        ExprKind::Call {
1610                            function: "read_first".to_owned(),
1611                            args: vec![],
1612                        },
1613                        Type::Number,
1614                    ),
1615                },
1616                command(Command::Echo, vec![variable("answer", Type::Number)], false),
1617            ],
1618            ..Program::default()
1619        };
1620        let safe_script = Bash.emit(&safe).expect("emit initialized global call");
1621        let safe_output = run_bash(&safe_script, None);
1622        assert!(
1623            safe_output.status.success(),
1624            "{}",
1625            String::from_utf8_lossy(&safe_output.stderr)
1626        );
1627        assert_eq!(String::from_utf8_lossy(&safe_output.stdout), "41\n");
1628
1629        let early = Program {
1630            functions: vec![Function {
1631                name: "read_later".to_owned(),
1632                params: vec![],
1633                return_type: Type::Number,
1634                body: vec![Stmt::Return(Some(variable("later", Type::Number)))],
1635            }],
1636            body: vec![
1637                Stmt::Let {
1638                    name: "early".to_owned(),
1639                    value: expr(
1640                        ExprKind::Call {
1641                            function: "read_later".to_owned(),
1642                            args: vec![],
1643                        },
1644                        Type::Number,
1645                    ),
1646                },
1647                Stmt::Let {
1648                    name: "later".to_owned(),
1649                    value: number(9),
1650                },
1651            ],
1652            ..Program::default()
1653        };
1654        let early_script = Bash.emit(&early).expect("emit guarded global call");
1655        let early_output = run_bash(&early_script, None);
1656        assert_eq!(early_output.status.code(), Some(1));
1657        assert!(
1658            String::from_utf8_lossy(&early_output.stderr)
1659                .contains("global `later` accessed before initialization")
1660        );
1661    }
1662
1663    #[test]
1664    fn instances_have_separate_mutable_fields_and_safe_field_symbols() {
1665        let this = || variable("__tsh_this", Type::Class("Counter".to_owned()));
1666        let this_count = || {
1667            expr(
1668                ExprKind::Field {
1669                    object: Box::new(this()),
1670                    class: "Counter".to_owned(),
1671                    field: "x-y;$(touch BAD)".to_owned(),
1672                },
1673                Type::Number,
1674            )
1675        };
1676        let increment = Function {
1677            name: "increment".to_owned(),
1678            params: vec![],
1679            return_type: Type::Number,
1680            body: vec![
1681                Stmt::Assign {
1682                    place: Place::Field {
1683                        object: this(),
1684                        class: "Counter".to_owned(),
1685                        field: "x-y;$(touch BAD)".to_owned(),
1686                    },
1687                    value: expr(
1688                        ExprKind::Binary {
1689                            op: "+".to_owned(),
1690                            left: Box::new(this_count()),
1691                            right: Box::new(number(1)),
1692                        },
1693                        Type::Number,
1694                    ),
1695                },
1696                Stmt::Return(Some(this_count())),
1697            ],
1698        };
1699        let class = Class {
1700            name: "Counter".to_owned(),
1701            fields: vec![Field {
1702                name: "x-y;$(touch BAD)".to_owned(),
1703                ty: Type::Number,
1704                initial: Some(number(4)),
1705            }],
1706            constructor: Function {
1707                name: "Counter".to_owned(),
1708                params: vec![],
1709                return_type: Type::Void,
1710                body: vec![],
1711            },
1712            methods: vec![Method {
1713                function: increment,
1714                is_static: false,
1715            }],
1716        };
1717        let instance = |name: &str| variable(name, Type::Class("Counter".to_owned()));
1718        let field = |name: &str| {
1719            expr(
1720                ExprKind::Field {
1721                    object: Box::new(instance(name)),
1722                    class: "Counter".to_owned(),
1723                    field: "x-y;$(touch BAD)".to_owned(),
1724                },
1725                Type::Number,
1726            )
1727        };
1728        let call_increment = |name: &str| {
1729            expr(
1730                ExprKind::Method {
1731                    object: Some(Box::new(instance(name))),
1732                    class: "Counter".to_owned(),
1733                    method: "increment".to_owned(),
1734                    args: vec![],
1735                },
1736                Type::Number,
1737            )
1738        };
1739        let program = Program {
1740            classes: vec![class],
1741            body: vec![
1742                Stmt::Let {
1743                    name: "first".to_owned(),
1744                    value: expr(
1745                        ExprKind::New {
1746                            class: "Counter".to_owned(),
1747                            args: vec![],
1748                        },
1749                        Type::Class("Counter".to_owned()),
1750                    ),
1751                },
1752                Stmt::Let {
1753                    name: "second".to_owned(),
1754                    value: expr(
1755                        ExprKind::New {
1756                            class: "Counter".to_owned(),
1757                            args: vec![],
1758                        },
1759                        Type::Class("Counter".to_owned()),
1760                    ),
1761                },
1762                Stmt::Expr(call_increment("first")),
1763                command(Command::Echo, vec![field("second"), field("first")], false),
1764            ],
1765            ..Program::default()
1766        };
1767        let script = Bash.emit(&program).expect("emit class");
1768        assert!(!script.contains("x-y;$(touch BAD)"));
1769        assert!(!script.contains("touch BAD"));
1770        let output = run_bash(&script, None);
1771        assert!(
1772            output.status.success(),
1773            "{}",
1774            String::from_utf8_lossy(&output.stderr)
1775        );
1776        assert_eq!(String::from_utf8_lossy(&output.stdout), "4 5\n");
1777    }
1778
1779    #[test]
1780    fn comments_only_and_empty_branches_stay_valid_bash() {
1781        let program = Program {
1782            body: vec![Stmt::If {
1783                condition: boolean(true),
1784                then_body: vec![],
1785                else_body: vec![Stmt::Comment("// comment only".to_owned())],
1786            }],
1787            ..Program::default()
1788        };
1789        let script = Bash.emit(&program).expect("emit empty branch");
1790        assert!(script.contains("then\n  :\nelse\n  # comment only\n  :\n"));
1791        let output = run_bash(&script, None);
1792        assert!(
1793            output.status.success(),
1794            "{}",
1795            String::from_utf8_lossy(&output.stderr)
1796        );
1797    }
1798
1799    #[test]
1800    fn booleans_print_as_language_values_and_strings_stay_literal() {
1801        let temp = tempfile::tempdir().expect("temporary directory");
1802        let hostile = "single' quote\n$(touch PWNED) * $HOME `touch PWNED`";
1803        let template = expr(
1804            ExprKind::Template(vec![
1805                string("text="),
1806                string(hostile),
1807                string("|"),
1808                boolean(false),
1809            ]),
1810            Type::String,
1811        );
1812        let variable_template = expr(
1813            ExprKind::Template(vec![string("flag="), variable("enabled", Type::Boolean)]),
1814            Type::String,
1815        );
1816        let program = Program {
1817            body: vec![
1818                Stmt::Let {
1819                    name: "enabled".to_owned(),
1820                    value: boolean(true),
1821                },
1822                command(Command::Echo, vec![boolean(true), template], false),
1823                command(Command::Echo, vec![variable_template], false),
1824            ],
1825            ..Program::default()
1826        };
1827        let script = Bash.emit(&program).expect("emit interpolation");
1828        let output = run_bash(&script, Some(temp.path()));
1829        assert!(
1830            output.status.success(),
1831            "{}",
1832            String::from_utf8_lossy(&output.stderr)
1833        );
1834        assert_eq!(
1835            String::from_utf8_lossy(&output.stdout),
1836            format!("true text={hostile}|false\nflag=true\n")
1837        );
1838        assert!(!temp.path().join("PWNED").exists());
1839    }
1840
1841    #[cfg(unix)]
1842    #[test]
1843    fn filesystem_commands_quote_leading_dash_operands_and_preserve_status() {
1844        use std::os::unix::fs::PermissionsExt;
1845
1846        let temp = tempfile::tempdir().expect("temporary directory");
1847        let path = temp.path().to_string_lossy().into_owned();
1848        let program = Program {
1849            body: vec![
1850                command(Command::Cd, vec![string(&path)], false),
1851                command(Command::Mkdir, vec![string("-p/nested")], true),
1852                command(
1853                    Command::Run,
1854                    vec![string("touch"), string("--"), string("-f")],
1855                    false,
1856                ),
1857                command(Command::Mv, vec![string("-f"), string("-g")], false),
1858                command(Command::Cp, vec![string("-g"), string("-h")], false),
1859                command(Command::Chmod, vec![string("-h"), number(493)], false),
1860                command(Command::Rm, vec![string("-g")], false),
1861                command(Command::Rm, vec![string("-p")], true),
1862            ],
1863            ..Program::default()
1864        };
1865        let script = Bash.emit(&program).expect("emit filesystem commands");
1866        assert!(script.contains("mkdir -p --"));
1867        assert!(script.contains("mv --"));
1868        assert!(script.contains("cp --"));
1869        assert!(script.contains("chmod --"));
1870        let output = run_bash(&script, None);
1871        assert!(
1872            output.status.success(),
1873            "{}",
1874            String::from_utf8_lossy(&output.stderr)
1875        );
1876        assert_eq!(
1877            std::fs::metadata(temp.path().join("-h"))
1878                .expect("chmod target")
1879                .permissions()
1880                .mode()
1881                & 0o777,
1882            0o755
1883        );
1884        assert!(!temp.path().join("-p").exists());
1885        assert!(!temp.path().join("-g").exists());
1886    }
1887
1888    #[test]
1889    fn failed_commands_exit_with_the_command_status() {
1890        let program = Program {
1891            body: vec![command(
1892                Command::Run,
1893                vec![string("bash"), string("-c"), string("exit 23")],
1894                false,
1895            )],
1896            ..Program::default()
1897        };
1898        let script = Bash.emit(&program).expect("emit failing command");
1899        let output = run_bash(&script, None);
1900        assert_eq!(output.status.code(), Some(23));
1901    }
1902}