typedshell 0.1.0

A typed TypeScript subset compiled to standalone Bash or other shell targets
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
//! PowerShell 7.4 emitter for the shared typed IR.
//!
//! Design notes:
//! - Native PowerShell `class` definitions back tsh classes; methods keep
//!   their mutations because objects are real references.
//! - tsh functions become PowerShell functions. Every call site captures the
//!   result (`$tmp = Name args...`) and every discarded value is assigned to
//!   `$null`, so intermediate pipeline output can never leak into a return
//!   value.
//! - IR variable names are globally unique, so lexical scoping needs no
//!   runtime support except one rule: assignments and reads of module-scope
//!   variables from inside functions, methods, and constructors use the
//!   `$script:` scope so mutations survive the call.
//! - Comparisons use the case-sensitive `-c*` operators to preserve tsh's
//!   case-sensitive string semantics. Integer division uses
//!   `[Math]::DivRem` so large `long` values stay exact and truncate toward
//!   zero, matching the Bash backend.

use std::collections::{HashMap, HashSet};

use crate::{
    backends::powershell::ps_quote,
    compiler::diagnostics::CompileError,
    ir::{Class, Command, Expr, ExprKind, Function, Method, Place, Program, Stmt, Type},
};

/// Entry point used by the `Backend` implementation.
pub fn emit_program(program: &Program) -> Result<String, CompileError> {
    validate_program(program)?;
    let metadata = Metadata::new(program);
    let mut emitter = Emitter::new(&metadata);
    let mut output = String::from(
        "# Generated by tsh. Requires PowerShell 7.4 or newer.\n$ErrorActionPreference = 'Continue'\n",
    );
    for class in &program.classes {
        output.push_str(&emitter.emit_class(class)?);
        output.push('\n');
    }
    for function in &program.functions {
        output.push_str(&emitter.emit_function(function)?);
        output.push('\n');
    }
    output.push_str(&emitter.emit_top_level(&program.body)?);
    Ok(output)
}

/// A lowered value: a PowerShell expression plus its static type.
#[derive(Debug, Clone)]
struct Value {
    /// PowerShell expression text (a variable, literal, or parenthesized op).
    expr: String,
    /// Temp variable holding the value, when one was allocated.
    var: Option<String>,
    ty: Type,
}

impl Value {
    fn plain(expr: impl Into<String>, ty: Type) -> Self {
        Self {
            expr: expr.into(),
            var: None,
            ty,
        }
    }

    fn temp(name: String, ty: Type) -> Self {
        Self {
            expr: format!("${name}"),
            var: Some(name),
            ty,
        }
    }
}

#[derive(Debug, Clone)]
struct Metadata<'a> {
    /// IR class name -> class definition.
    classes: HashMap<&'a str, &'a Class>,
    /// (class IR name, method IR name) that are static.
    statics: HashSet<(&'a str, &'a str)>,
    /// (class IR name, source field name) -> PowerShell property name.
    properties: HashMap<(&'a str, &'a str), String>,
    /// Module-scope variable names; these live in script scope.
    globals: HashSet<&'a str>,
}

impl<'a> Metadata<'a> {
    fn new(program: &'a Program) -> Self {
        let mut classes = HashMap::new();
        let mut statics = HashSet::new();
        for class in &program.classes {
            classes.insert(class.name.as_str(), class);
            for method in &class.methods {
                if method.is_static {
                    statics.insert((class.name.as_str(), method.function.name.as_str()));
                }
            }
        }
        let mut properties = HashMap::new();
        for class in &program.classes {
            let mut used: HashSet<String> = HashSet::new();
            for field in &class.fields {
                let mut candidate = if is_safe_member(&field.name) {
                    field.name.clone()
                } else {
                    format!("__tsh_field_{}", hex_bytes(field.name.as_bytes()))
                };
                while !used.insert(candidate.to_ascii_lowercase()) {
                    candidate.push('_');
                }
                properties.insert((class.name.as_str(), field.name.as_str()), candidate);
            }
        }
        let mut globals = HashSet::new();
        for statement in &program.body {
            if let Stmt::Let { name, .. } = statement {
                globals.insert(name.as_str());
            }
        }
        Self {
            classes,
            statics,
            properties,
            globals,
        }
    }

    fn property(&self, class: &str, field: &str) -> Result<String, CompileError> {
        self.properties
            .get(&(class, field))
            .cloned()
            .ok_or_else(|| {
                CompileError::plain(format!("unknown field `{class}.{field}` in PowerShell IR"))
            })
    }

    fn is_static(&self, class: &str, method: &str) -> Result<bool, CompileError> {
        self.classes.get(class).map(|_| ()).ok_or_else(|| {
            CompileError::plain(format!("unknown class `{class}` in PowerShell IR"))
        })?;
        Ok(self.statics.contains(&(class, method)))
    }
}

#[derive(Debug, Clone)]
enum LoopMode {
    While,
    For(Vec<Stmt>),
}

struct Emitter<'a> {
    metadata: &'a Metadata<'a>,
    code: String,
    indent: usize,
    next_temp: usize,
    /// True inside functions, methods, and constructors.
    in_function: bool,
    loops: Vec<LoopMode>,
}

impl<'a> Emitter<'a> {
    fn new(metadata: &'a Metadata<'a>) -> Self {
        Self {
            metadata,
            code: String::new(),
            indent: 0,
            next_temp: 0,
            in_function: false,
            loops: Vec::new(),
        }
    }

    /// Run `emit` with a fresh buffer and return the produced code.
    fn block(
        &mut self,
        in_function: bool,
        indent: usize,
        emit: impl FnOnce(&mut Self) -> Result<(), CompileError>,
    ) -> Result<String, CompileError> {
        let saved_code = std::mem::take(&mut self.code);
        let saved_indent = self.indent;
        let saved_function = self.in_function;
        let saved_loops = std::mem::take(&mut self.loops);
        self.indent = indent;
        self.in_function = in_function;
        let result = emit(self);
        let block = std::mem::replace(&mut self.code, saved_code);
        self.indent = saved_indent;
        self.in_function = saved_function;
        self.loops = saved_loops;
        result.map(|()| block)
    }

    fn line(&mut self, text: &str) {
        for _ in 0..self.indent {
            self.code.push_str("    ");
        }
        self.code.push_str(text);
        self.code.push('\n');
    }

    fn fresh_temp(&mut self) -> String {
        let name = format!("__tsh_tmp_{}", self.next_temp);
        self.next_temp += 1;
        name
    }

    /// `$this` is automatic; module-scope names need `$script:` inside
    /// functions so reads and writes reach script scope.
    fn variable(&self, name: &str) -> String {
        if name == "__tsh_this" {
            return "$this".to_owned();
        }
        if self.in_function && self.metadata.globals.contains(name) {
            format!("$script:{name}")
        } else {
            format!("${name}")
        }
    }

    fn emit_top_level(&mut self, statements: &[Stmt]) -> Result<String, CompileError> {
        let mut emitter = Emitter::new(self.metadata);
        emitter.next_temp = self.next_temp;
        emitter.emit_statements(statements)?;
        self.next_temp = emitter.next_temp;
        Ok(emitter.code)
    }

    fn emit_class(&mut self, class: &Class) -> Result<String, CompileError> {
        let mut output = format!("class {} {{\n", class.name);
        for field in &class.fields {
            let property = self.metadata.property(&class.name, &field.name)?;
            output.push_str(&format!(
                "    [{}]${}\n",
                ps_class_type(&field.ty)?,
                property
            ));
        }
        // Constructors and methods are emitted through a sub-emitter so temp
        // numbering stays globally unique.
        let mut sub = Emitter::new(self.metadata);
        sub.next_temp = self.next_temp;
        let constructor = sub.emit_constructor(class)?;
        let mut methods = Vec::new();
        for method in &class.methods {
            methods.push(sub.emit_method(class, method)?);
        }
        self.next_temp = sub.next_temp;
        output.push_str(&constructor);
        for method in methods {
            output.push_str(&method);
        }
        output.push_str("}\n");
        Ok(output)
    }

    fn emit_constructor(&mut self, class: &Class) -> Result<String, CompileError> {
        let mut params = Vec::new();
        for param in &class.constructor.params {
            params.push(format!("[{}]${}", ps_class_type(&param.ty)?, param.name));
        }
        let body = self.block(true, 2, |emitter| {
            // Field initializers run in source order before the constructor
            // body, matching the Bash backend.
            for field in &class.fields {
                let property = emitter
                    .metadata
                    .property(&class.name, &field.name)?
                    .to_owned();
                if let Some(initial) = &field.initial {
                    let value = emitter.emit_expr(initial)?;
                    emitter.line(&format!("$this.{property} = {}", value.expr));
                } else {
                    emitter.line(&format!("$this.{property} = {}", default_value(&field.ty)));
                }
            }
            emitter.emit_statements(&class.constructor.body)
        })?;
        Ok(format!(
            "    {}({}) {{\n{}    }}\n",
            class.name,
            params.join(", "),
            body
        ))
    }

    fn emit_method(&mut self, _class: &Class, method: &Method) -> Result<String, CompileError> {
        let function = &method.function;
        let mut params = Vec::new();
        for param in &function.params {
            params.push(format!("[{}]${}", ps_class_type(&param.ty)?, param.name));
        }
        let body = self.block(true, 2, |emitter| emitter.emit_statements(&function.body))?;
        let prefix = if method.is_static { "static " } else { "" };
        Ok(format!(
            "    {}[{}] {}({}) {{\n{}    }}\n",
            prefix,
            ps_class_type(&function.return_type)?,
            function.name,
            params.join(", "),
            body
        ))
    }

    fn emit_function(&mut self, function: &Function) -> Result<String, CompileError> {
        let mut sub = Emitter::new(self.metadata);
        sub.next_temp = self.next_temp;
        let body = sub.block(true, 1, |emitter| emitter.emit_statements(&function.body))?;
        self.next_temp = sub.next_temp;
        let mut output = format!("function __tsh_fn_{} {{\n", function.name);
        if function.params.is_empty() {
            output.push_str(&body);
        } else {
            let mut params = Vec::new();
            for param in &function.params {
                params.push(format!("[{}]${}", ps_class_type(&param.ty)?, param.name));
            }
            output.push_str(&format!("    param({})\n", params.join(", ")));
            output.push_str(&body);
        }
        output.push_str("}\n");
        Ok(output)
    }

    fn emit_statements(&mut self, statements: &[Stmt]) -> Result<(), CompileError> {
        for statement in statements {
            self.emit_statement(statement)?;
        }
        Ok(())
    }

    fn emit_statement(&mut self, statement: &Stmt) -> Result<(), CompileError> {
        match statement {
            Stmt::Let { name, value } => {
                let value = self.emit_expr(value)?;
                self.line(&format!("{} = {}", self.variable(name), value.expr));
            }
            Stmt::Assign { place, value } => self.emit_assignment(place, value)?,
            Stmt::Expr(expression) => {
                // Discard the value through `$null` so calls made for their
                // effects never leak output into an enclosing function.
                let value = self.emit_expr(expression)?;
                self.line(&format!("$null = {}", value.expr));
            }
            Stmt::If {
                condition,
                then_body,
                else_body,
            } => {
                let condition = self.emit_expr(condition)?;
                self.ensure_boolean(&condition)?;
                self.line(&format!("if ({}) {{", condition.expr));
                self.indent += 1;
                self.emit_statements(then_body)?;
                self.indent -= 1;
                if else_body.is_empty() {
                    self.line("}");
                } else {
                    self.line("} else {");
                    self.indent += 1;
                    self.emit_statements(else_body)?;
                    self.indent -= 1;
                    self.line("}");
                }
            }
            Stmt::While { condition, body } => {
                self.line("while ($true) {");
                self.indent += 1;
                let condition = self.emit_expr(condition)?;
                self.ensure_boolean(&condition)?;
                self.line(&format!("if (-not ({})) {{ break }}", condition.expr));
                self.loops.push(LoopMode::While);
                self.emit_statements(body)?;
                self.loops.pop();
                self.indent -= 1;
                self.line("}");
            }
            Stmt::For {
                init,
                condition,
                update,
                body,
            } => {
                self.emit_statements(init)?;
                self.line("while ($true) {");
                self.indent += 1;
                if let Some(condition) = condition {
                    let condition = self.emit_expr(condition)?;
                    self.ensure_boolean(&condition)?;
                    self.line(&format!("if (-not ({})) {{ break }}", condition.expr));
                }
                self.loops.push(LoopMode::For(update.clone()));
                self.emit_statements(body)?;
                self.loops.pop();
                self.emit_statements(update)?;
                self.indent -= 1;
                self.line("}");
            }
            Stmt::Return(value) => {
                if let Some(value) = value {
                    let value = self.emit_expr(value)?;
                    self.line(&format!("return {}", value.expr));
                } else {
                    self.line("return");
                }
            }
            Stmt::Break => {
                if self.loops.is_empty() {
                    return Err(CompileError::plain(
                        "`break` is not inside a loop in PowerShell IR",
                    ));
                }
                self.line("break");
            }
            Stmt::Continue => {
                let mode = self.loops.last().cloned().ok_or_else(|| {
                    CompileError::plain("`continue` is not inside a loop in PowerShell IR")
                })?;
                if let LoopMode::For(update) = mode {
                    // `continue` jumps to the loop condition; run the
                    // for-update first so it matches the IR semantics.
                    self.emit_statements(&update)?;
                }
                self.line("continue");
            }
            Stmt::Command {
                kind,
                args,
                recursive,
            } => self.emit_command(*kind, args, *recursive)?,
            Stmt::Raw(raw) => {
                self.code.push_str(raw);
                if !raw.ends_with('\n') {
                    self.code.push('\n');
                }
            }
            Stmt::Comment(comment) => self.emit_comment(comment),
            Stmt::Block(body) => self.emit_statements(body)?,
        }
        Ok(())
    }

    fn emit_comment(&mut self, comment: &str) {
        let lines = crate::backends::shell_comment_lines(comment);
        if lines.is_empty() {
            self.line("#");
            return;
        }
        for text in lines {
            self.line(&format!("# {text}"));
        }
    }

    fn emit_assignment(&mut self, place: &Place, expression: &Expr) -> Result<(), CompileError> {
        match place {
            Place::Variable(name) => {
                let value = self.emit_expr(expression)?;
                self.line(&format!("{} = {}", self.variable(name), value.expr));
            }
            Place::Field {
                object,
                class,
                field,
            } => {
                let property = self.metadata.property(class, field)?.to_owned();
                let object_value = self.emit_expr(object)?;
                let object = self.capture_if_variable(object, object_value);
                let value = self.emit_expr(expression)?;
                self.line(&format!("{}.{property} = {}", object.expr, value.expr));
            }
        }
        Ok(())
    }

    fn emit_expr(&mut self, expression: &Expr) -> Result<Value, CompileError> {
        match &expression.kind {
            ExprKind::String(value) => Ok(Value::plain(ps_quote(value), expression.ty.clone())),
            ExprKind::Number(value) => {
                if *value == i64::MIN {
                    Ok(Value::plain("([long]::MinValue)", expression.ty.clone()))
                } else {
                    Ok(Value::plain(value.to_string(), expression.ty.clone()))
                }
            }
            ExprKind::Boolean(value) => Ok(Value::plain(
                if *value { "$true" } else { "$false" },
                expression.ty.clone(),
            )),
            ExprKind::Variable(name) => {
                Ok(Value::plain(self.variable(name), expression.ty.clone()))
            }
            ExprKind::Template(parts) => self.emit_template(parts, expression.ty.clone()),
            ExprKind::Binary { op, left, right } => {
                self.emit_binary(op, left, right, expression.ty.clone())
            }
            ExprKind::Unary { op, value } => self.emit_unary(op, value, expression.ty.clone()),
            ExprKind::Call { function, args } => {
                self.emit_call(function, args, expression.ty.clone())
            }
            ExprKind::New { class, args } => self.emit_new(class, args),
            ExprKind::Field {
                object,
                class,
                field,
            } => {
                let property = self.metadata.property(class, field)?.to_owned();
                let object_value = self.emit_expr(object)?;
                let object = self.capture_if_variable(object, object_value);
                let temp = self.fresh_temp();
                self.line(&format!("${temp} = {}.{property}", object.expr));
                Ok(Value::temp(temp, expression.ty.clone()))
            }
            ExprKind::Method {
                object,
                class,
                method,
                args,
            } => self.emit_method_call(
                object.as_deref(),
                class,
                method,
                args,
                expression.ty.clone(),
            ),
            ExprKind::Env(key) => self.emit_env(key, expression.ty.clone()),
        }
    }

    fn emit_template(&mut self, parts: &[Expr], result_type: Type) -> Result<Value, CompileError> {
        let result = self.fresh_temp();
        self.line(&format!("${result} = ''"));
        for part in parts {
            if matches!(part.ty, Type::Void) {
                return Err(CompileError::plain(
                    "cannot interpolate a void expression in PowerShell IR",
                ));
            }
            let mut value = self.emit_expr(part)?;
            if matches!(value.ty, Type::Boolean) {
                value = self.boolean_as_text(value)?;
            }
            self.line(&format!("${result} = (${result} + {})", value.expr));
        }
        Ok(Value::temp(result, result_type))
    }

    fn emit_binary(
        &mut self,
        op: &str,
        left: &Expr,
        right: &Expr,
        result_type: Type,
    ) -> Result<Value, CompileError> {
        if op == "&&" || op == "||" {
            return self.emit_logical(op, left, right, result_type);
        }
        let left_value = self.emit_expr(left)?;
        let mut left = self.capture_if_variable(left, left_value);
        if op == "+" && matches!(result_type, Type::String) && matches!(left.ty, Type::Boolean) {
            left = self.boolean_as_text(left)?;
        }
        let right_value = self.emit_expr(right)?;
        let mut right = self.capture_if_variable(right, right_value);
        if op == "+" && matches!(result_type, Type::String) && matches!(right.ty, Type::Boolean) {
            right = self.boolean_as_text(right)?;
        }

        if op == "+" && matches!(result_type, Type::String) {
            return Ok(Value::plain(
                format!("({} + {})", left.expr, right.expr),
                result_type,
            ));
        }
        if is_comparison(op) {
            return Ok(Value::plain(
                format!("({} {} {})", left.expr, ps_comparison(op)?, right.expr),
                result_type,
            ));
        }
        match op {
            "+" | "-" | "*" | "%" => Ok(Value::plain(
                format!("({} {} {})", left.expr, op, right.expr),
                result_type,
            )),
            "/" => {
                // PowerShell `/` promotes integers to double, so exact
                // 64-bit division needs `DivRem`, which also truncates toward
                // zero like the Bash backend.
                let result = self.fresh_temp();
                let remainder = self.fresh_temp();
                self.line(&format!("${remainder} = 0"));
                self.line(&format!(
                    "${result} = [Math]::DivRem({}, {}, [ref]${remainder})",
                    left.expr, right.expr
                ));
                Ok(Value::temp(result, result_type))
            }
            _ => Err(CompileError::plain(format!(
                "unsupported PowerShell binary operator `{op}`"
            ))),
        }
    }

    fn emit_logical(
        &mut self,
        op: &str,
        left: &Expr,
        right: &Expr,
        result_type: Type,
    ) -> Result<Value, CompileError> {
        if !matches!(result_type, Type::Boolean) {
            return Err(CompileError::plain(
                "logical PowerShell IR expression must have boolean type",
            ));
        }
        let left = self.emit_expr(left)?;
        self.ensure_boolean(&left)?;
        let result = self.fresh_temp();
        match op {
            "&&" => {
                self.line(&format!("${result} = $false"));
                self.line(&format!("if ({}) {{", left.expr));
                self.indent += 1;
                let right = self.emit_expr(right)?;
                self.ensure_boolean(&right)?;
                self.line(&format!("${result} = {}", right.expr));
                self.indent -= 1;
                self.line("}");
            }
            "||" => {
                self.line(&format!("${result} = $true"));
                self.line(&format!("if (-not ({})) {{", left.expr));
                self.indent += 1;
                let right = self.emit_expr(right)?;
                self.ensure_boolean(&right)?;
                self.line(&format!("${result} = {}", right.expr));
                self.indent -= 1;
                self.line("}");
            }
            _ => unreachable!(),
        }
        Ok(Value::temp(result, result_type))
    }

    fn emit_unary(
        &mut self,
        op: &str,
        expression: &Expr,
        result_type: Type,
    ) -> Result<Value, CompileError> {
        let value = self.emit_expr(expression)?;
        let value = self.capture_if_variable(expression, value);
        match op {
            "!" => Ok(Value::plain(format!("(-not {})", value.expr), result_type)),
            "-" => Ok(Value::plain(format!("(-{})", value.expr), result_type)),
            "+" => Ok(Value::plain(format!("(+{})", value.expr), result_type)),
            _ => Err(CompileError::plain(format!(
                "unsupported PowerShell unary operator `{op}`"
            ))),
        }
    }

    fn emit_call(
        &mut self,
        function: &str,
        args: &[Expr],
        result_type: Type,
    ) -> Result<Value, CompileError> {
        let args = self.capture_arguments(args)?;
        let mut call = format!("__tsh_fn_{function}");
        for argument in &args {
            call.push(' ');
            call.push_str(&argument.expr);
        }
        let result = self.fresh_temp();
        self.line(&format!("${result} = {call}"));
        Ok(Value::temp(result, result_type))
    }

    fn emit_new(&mut self, class: &str, args: &[Expr]) -> Result<Value, CompileError> {
        if !self.metadata.classes.contains_key(class) {
            return Err(CompileError::plain(format!(
                "unknown class `{class}` in PowerShell IR"
            )));
        }
        let args = self.capture_arguments(args)?;
        let rendered: Vec<&str> = args.iter().map(|argument| argument.expr.as_str()).collect();
        let result = self.fresh_temp();
        self.line(&format!(
            "${result} = [{class}]::new({})",
            rendered.join(", ")
        ));
        Ok(Value::temp(result, Type::Class(class.to_owned())))
    }

    fn emit_method_call(
        &mut self,
        object: Option<&Expr>,
        class: &str,
        method: &str,
        args: &[Expr],
        result_type: Type,
    ) -> Result<Value, CompileError> {
        let is_static = self.metadata.is_static(class, method)?;
        let object = match (object, is_static) {
            (Some(object), false) => {
                let object_value = self.emit_expr(object)?;
                Some(self.capture_if_variable(object, object_value))
            }
            (None, false) => {
                return Err(CompileError::plain(format!(
                    "instance method `{class}.{method}` has no receiver in PowerShell IR"
                )));
            }
            (Some(_), true) => {
                return Err(CompileError::plain(format!(
                    "static method `{class}.{method}` unexpectedly has a receiver in PowerShell IR"
                )));
            }
            (None, true) => None,
        };
        let args = self.capture_arguments(args)?;
        let rendered: Vec<&str> = args.iter().map(|argument| argument.expr.as_str()).collect();
        let joined = rendered.join(", ");
        let result = self.fresh_temp();
        if let Some(object) = object {
            self.line(&format!("${result} = {}.{method}({joined})", object.expr));
        } else {
            self.line(&format!("${result} = [{class}]::{method}({joined})"));
        }
        Ok(Value::temp(result, result_type))
    }

    fn emit_env(&mut self, expression: &Expr, result_type: Type) -> Result<Value, CompileError> {
        let key = self.emit_expr(expression)?;
        let key = self.capture(key);
        let lookup = self.fresh_temp();
        let result = self.fresh_temp();
        self.line(&format!("${result} = ''"));
        self.line(&format!(
            "${lookup} = [System.Environment]::GetEnvironmentVariable({})",
            key.expr
        ));
        self.line(&format!(
            "if ($null -ne ${lookup}) {{ ${result} = ${lookup} }}"
        ));
        Ok(Value::temp(result, result_type))
    }

    fn emit_command(
        &mut self,
        kind: Command,
        args: &[Expr],
        recursive: bool,
    ) -> Result<(), CompileError> {
        match kind {
            Command::Exit => {
                if args.len() > 1 {
                    return Err(CompileError::plain(
                        "`exit` accepts at most one argument in PowerShell IR",
                    ));
                }
                if let Some(value) = args.first() {
                    let value = self.emit_expr(value)?;
                    let value = self.capture(value);
                    self.line(&format!("exit {}", value.expr));
                } else {
                    self.line("exit 0");
                }
            }
            Command::Echo => {
                let values = self.capture_arguments(args)?;
                if values.is_empty() {
                    self.line("[Console]::WriteLine('')");
                    return Ok(());
                }
                let result = self.fresh_temp();
                self.line(&format!("${result} = ''"));
                for (index, value) in values.iter().enumerate() {
                    let value = if matches!(value.ty, Type::Boolean) {
                        self.boolean_as_text(value.clone())?
                    } else {
                        value.clone()
                    };
                    if index > 0 {
                        self.line(&format!("${result} = (${result} + ' ')"));
                    }
                    self.line(&format!("${result} = (${result} + {})", value.expr));
                }
                self.line(&format!("[Console]::WriteLine(${result})"));
            }
            Command::Mkdir => {
                if args.is_empty() {
                    return Err(CompileError::plain(
                        "`mkdir` expects at least one path in PowerShell IR",
                    ));
                }
                let values = self.capture_arguments(args)?;
                for value in values {
                    self.ensure_string(&value, "mkdir")?;
                    let flag = if recursive { " -Force" } else { "" };
                    self.line(&format!(
                        "$null = New-Item -ItemType Directory -Path {}{flag}",
                        value.expr
                    ));
                    self.checked("mkdir");
                }
            }
            Command::Rm => {
                if args.is_empty() {
                    return Err(CompileError::plain(
                        "`rm` expects at least one path in PowerShell IR",
                    ));
                }
                let values = self.capture_arguments(args)?;
                for value in values {
                    self.ensure_string(&value, "rm")?;
                    if recursive {
                        self.line(&format!(
                            "Remove-Item -LiteralPath {} -Recurse -Force -Confirm:$false",
                            value.expr
                        ));
                    } else {
                        // Bash `rm` without `-r` refuses directories, even
                        // empty ones; PowerShell would remove an empty
                        // directory, so guard it explicitly.
                        self.line(&format!(
                            "if (Test-Path -LiteralPath {} -PathType Container) {{ exit 1 }}",
                            value.expr
                        ));
                        self.line(&format!(
                            "Remove-Item -LiteralPath {} -Force -Confirm:$false",
                            value.expr
                        ));
                    }
                    self.checked("rm");
                }
            }
            Command::Cp => {
                if args.len() != 2 {
                    return Err(CompileError::plain(
                        "`cp` expects exactly two paths in PowerShell IR",
                    ));
                }
                let values = self.capture_arguments(args)?;
                for value in &values {
                    self.ensure_string(value, "cp")?;
                }
                self.line(&format!(
                    "Copy-Item -LiteralPath {} -Destination {} -Force -Confirm:$false",
                    values[0].expr, values[1].expr
                ));
                self.checked("cp");
            }
            Command::Mv => {
                if args.len() != 2 {
                    return Err(CompileError::plain(
                        "`mv` expects exactly two paths in PowerShell IR",
                    ));
                }
                let values = self.capture_arguments(args)?;
                for value in &values {
                    self.ensure_string(value, "mv")?;
                }
                self.line(&format!(
                    "Move-Item -LiteralPath {} -Destination {} -Force -Confirm:$false",
                    values[0].expr, values[1].expr
                ));
                self.checked("mv");
            }
            Command::Cd => {
                if args.len() != 1 {
                    return Err(CompileError::plain(
                        "`cd` expects exactly one path in PowerShell IR",
                    ));
                }
                let values = self.capture_arguments(args)?;
                self.ensure_string(&values[0], "cd")?;
                self.line(&format!("Set-Location -LiteralPath {}", values[0].expr));
                self.checked("cd");
                // `Set-Location` does not move the process working directory,
                // so child processes (and .NET file APIs) would still resolve
                // relative paths against the old directory. Sync it so `cd`
                // matches the Bash backend.
                self.line("[Environment]::CurrentDirectory = (Get-Location).Path");
            }
            Command::Run => {
                if args.is_empty() {
                    return Err(CompileError::plain(
                        "`run` needs a command in PowerShell IR",
                    ));
                }
                let mut values = Vec::with_capacity(args.len());
                for argument in args {
                    let value = self.emit_expr(argument)?;
                    self.ensure_string(&value, "run")?;
                    values.push(self.capture_if_variable(argument, value));
                }
                let rendered: Vec<&str> = values[1..]
                    .iter()
                    .map(|value| value.expr.as_str())
                    .collect();
                // PowerShell expands wildcards in arguments passed to native
                // commands via `&`, so external processes are started through
                // .NET instead: `ArgumentList` carries every argument exactly,
                // stdio and the working directory are inherited, and the real
                // exit code is propagated.
                let info = self.fresh_temp();
                let process = self.fresh_temp();
                let item = self.fresh_temp();
                self.line(&format!(
                    "${info} = New-Object System.Diagnostics.ProcessStartInfo"
                ));
                self.line(&format!("${info}.FileName = {}", values[0].expr));
                self.line(&format!("${info}.UseShellExecute = $false"));
                self.line(&format!(
                    "foreach (${item} in @({})) {{ ${info}.ArgumentList.Add(${item}) }}",
                    rendered.join(", ")
                ));
                self.line("try {");
                self.indent += 1;
                self.line(&format!(
                    "${process} = [System.Diagnostics.Process]::Start(${info})"
                ));
                self.indent -= 1;
                self.line("} catch {");
                self.indent += 1;
                self.line("exit 1");
                self.indent -= 1;
                self.line("}");
                self.line(&format!("${process}.WaitForExit()"));
                self.line(&format!(
                    "if (${process}.ExitCode -ne 0) {{ exit ${process}.ExitCode }}"
                ));
            }
            Command::Chmod => {
                if args.len() != 2 {
                    return Err(CompileError::plain(
                        "`chmod` expects path and mode arguments in PowerShell IR",
                    ));
                }
                if recursive {
                    return Err(CompileError::plain(
                        "recursive `chmod` is not supported on the PowerShell target",
                    ));
                }
                self.ensure_string_arg(&args[0], "chmod")?;
                let path_value = self.emit_expr(&args[0])?;
                let path = self.capture_if_variable(&args[0], path_value);
                if let ExprKind::Number(decimal) = &args[1].kind {
                    if *decimal < 0 {
                        return Err(CompileError::plain(
                            "chmod mode cannot be negative in PowerShell IR",
                        ));
                    }
                    self.line(&format!(
                        "[System.IO.File]::SetUnixFileMode({}, {decimal})",
                        path.expr
                    ));
                } else if matches!(args[1].ty, Type::String) {
                    return Err(CompileError::plain(
                        "string `chmod` modes are not supported on the PowerShell target; use a numeric mode",
                    ));
                } else {
                    let mode_value = self.emit_expr(&args[1])?;
                    let mode = self.capture_if_variable(&args[1], mode_value);
                    self.line(&format!(
                        "[System.IO.File]::SetUnixFileMode({}, {})",
                        path.expr, mode.expr
                    ));
                }
                self.checked("chmod");
            }
        }
        Ok(())
    }

    /// Exit 1 when the previous cmdlet failed. Native commands (`run`)
    /// handle their own status codes instead.
    fn checked(&mut self, command: &str) {
        let _ = command;
        self.line("if (-not $?) { exit 1 }");
    }

    fn capture_arguments(&mut self, args: &[Expr]) -> Result<Vec<Value>, CompileError> {
        let mut values = Vec::with_capacity(args.len());
        for argument in args {
            let value = self.emit_expr(argument)?;
            values.push(self.capture_if_variable(argument, value));
        }
        Ok(values)
    }

    fn capture_if_variable(&mut self, expression: &Expr, value: Value) -> Value {
        if matches!(expression.kind, ExprKind::Variable(_)) {
            self.capture(value)
        } else {
            value
        }
    }

    fn capture(&mut self, value: Value) -> Value {
        let temp = self.fresh_temp();
        self.line(&format!("${temp} = {}", value.expr));
        Value::temp(temp, value.ty)
    }

    fn boolean_as_text(&mut self, value: Value) -> Result<Value, CompileError> {
        if !matches!(value.ty, Type::Boolean) {
            return Ok(value);
        }
        if value.var.is_none() {
            if value.expr == "$true" {
                return Ok(Value::plain(ps_quote("true"), Type::String));
            }
            if value.expr == "$false" {
                return Ok(Value::plain(ps_quote("false"), Type::String));
            }
        }
        let source = if value.var.is_some() {
            value
        } else {
            self.capture(value)
        };
        let result = self.fresh_temp();
        self.line(&format!("${result} = ''"));
        self.line(&format!("if ({}) {{ ${result} = 'true' }}", source.expr));
        self.line(&format!("else {{ ${result} = 'false' }}"));
        Ok(Value::temp(result, Type::String))
    }

    fn ensure_boolean(&self, value: &Value) -> Result<(), CompileError> {
        if matches!(value.ty, Type::Boolean) {
            Ok(())
        } else {
            Err(CompileError::plain(
                "PowerShell condition must have boolean type",
            ))
        }
    }

    fn ensure_string(&self, value: &Value, command: &str) -> Result<(), CompileError> {
        if matches!(value.ty, Type::String) {
            Ok(())
        } else {
            Err(CompileError::plain(format!(
                "`{command}` expects string arguments in PowerShell IR"
            )))
        }
    }

    fn ensure_string_arg(&mut self, expression: &Expr, command: &str) -> Result<(), CompileError> {
        if matches!(expression.ty, Type::String) {
            Ok(())
        } else {
            Err(CompileError::plain(format!(
                "`{command}` expects string arguments in PowerShell IR"
            )))
        }
    }
}

fn ps_type(ty: &Type) -> Result<&'static str, CompileError> {
    match ty {
        Type::String => Ok("string"),
        Type::Number => Ok("long"),
        Type::Boolean => Ok("bool"),
        Type::Void => Ok("void"),
        Type::Class(_) => Err(CompileError::plain(
            "class-typed PowerShell declarations need their class name",
        )),
    }
}

fn ps_class_type(ty: &Type) -> Result<String, CompileError> {
    match ty {
        Type::Class(name) => Ok(name.clone()),
        other => ps_type(other).map(str::to_owned),
    }
}

fn default_value(ty: &Type) -> &'static str {
    match ty {
        Type::Number => "0",
        Type::Boolean => "$false",
        Type::String => "''",
        Type::Void => "$null",
        Type::Class(_) => "$null",
    }
}

fn is_comparison(op: &str) -> bool {
    matches!(op, "==" | "===" | "!=" | "!==" | "<" | "<=" | ">" | ">=")
}

/// Case-sensitive operators: tsh strings compare case-sensitively, while
/// PowerShell's default comparison operators ignore case.
fn ps_comparison(op: &str) -> Result<&'static str, CompileError> {
    match op {
        "==" | "===" => Ok("-ceq"),
        "!=" | "!==" => Ok("-cne"),
        "<" => Ok("-clt"),
        "<=" => Ok("-cle"),
        ">" => Ok("-cgt"),
        ">=" => Ok("-cge"),
        _ => Err(CompileError::plain(format!(
            "unsupported PowerShell comparison operator `{op}`"
        ))),
    }
}

fn is_safe_member(name: &str) -> bool {
    let mut bytes = name.bytes();
    match bytes.next() {
        Some(byte) if byte == b'_' || byte.is_ascii_alphabetic() => {}
        _ => return false,
    }
    bytes.all(|byte| byte == b'_' || byte.is_ascii_alphanumeric())
}

fn hex_bytes(bytes: &[u8]) -> String {
    bytes.iter().map(|byte| format!("{byte:02x}")).collect()
}

fn is_safe_identifier(name: &str) -> bool {
    let mut bytes = name.bytes();
    let valid_start = bytes
        .next()
        .is_some_and(|byte| byte == b'_' || byte.is_ascii_alphabetic());
    valid_start && bytes.all(|byte| byte == b'_' || byte.is_ascii_alphanumeric())
}

fn validate_program(program: &Program) -> Result<(), CompileError> {
    for function in &program.functions {
        validate_function(function)?;
    }
    for class in &program.classes {
        if !is_safe_identifier(&class.name) {
            return Err(CompileError::plain(format!(
                "unsafe PowerShell class name `{}`",
                class.name
            )));
        }
        for field in &class.fields {
            if let Some(initial) = &field.initial {
                validate_expr(initial)?;
            }
        }
        validate_function(&class.constructor)?;
        for method in &class.methods {
            validate_function(&method.function)?;
        }
    }
    validate_statements(&program.body)
}

fn validate_function(function: &crate::ir::Function) -> Result<(), CompileError> {
    if !is_safe_identifier(&function.name) {
        return Err(CompileError::plain(format!(
            "unsafe PowerShell function name `{}`",
            function.name
        )));
    }
    for param in &function.params {
        if !is_safe_identifier(&param.name) {
            return Err(CompileError::plain(format!(
                "unsafe PowerShell parameter name `{}`",
                param.name
            )));
        }
    }
    validate_statements(&function.body)
}

fn validate_statements(statements: &[Stmt]) -> Result<(), CompileError> {
    for statement in statements {
        match statement {
            Stmt::Let { name, value } => {
                if !is_safe_identifier(name) {
                    return Err(CompileError::plain(format!(
                        "unsafe PowerShell variable name `{name}`"
                    )));
                }
                validate_expr(value)?;
            }
            Stmt::Assign { place, value } => {
                match place {
                    Place::Variable(name) => {
                        if !is_safe_identifier(name) {
                            return Err(CompileError::plain(format!(
                                "unsafe PowerShell variable name `{name}`"
                            )));
                        }
                    }
                    Place::Field { object, class, .. } => {
                        if !is_safe_identifier(class) {
                            return Err(CompileError::plain(format!(
                                "unsafe PowerShell class name `{class}`"
                            )));
                        }
                        validate_expr(object)?;
                    }
                }
                validate_expr(value)?;
            }
            Stmt::Expr(expression) | Stmt::Return(Some(expression)) => validate_expr(expression)?,
            Stmt::If {
                condition,
                then_body,
                else_body,
            } => {
                validate_expr(condition)?;
                validate_statements(then_body)?;
                validate_statements(else_body)?;
            }
            Stmt::While { condition, body } => {
                validate_expr(condition)?;
                validate_statements(body)?;
            }
            Stmt::For {
                init,
                condition,
                update,
                body,
            } => {
                validate_statements(init)?;
                if let Some(condition) = condition {
                    validate_expr(condition)?;
                }
                validate_statements(update)?;
                validate_statements(body)?;
            }
            Stmt::Command { args, .. } => {
                for argument in args {
                    validate_expr(argument)?;
                }
            }
            Stmt::Block(body) => validate_statements(body)?,
            Stmt::Return(None) | Stmt::Break | Stmt::Continue | Stmt::Raw(_) | Stmt::Comment(_) => {
            }
        }
    }
    Ok(())
}

fn validate_expr(expression: &Expr) -> Result<(), CompileError> {
    match &expression.kind {
        ExprKind::String(_) | ExprKind::Number(_) | ExprKind::Boolean(_) => {}
        ExprKind::Variable(name) => {
            if name != "__tsh_this" && !is_safe_identifier(name) {
                return Err(CompileError::plain(format!(
                    "unsafe PowerShell variable name `{name}`"
                )));
            }
        }
        ExprKind::Template(parts) => {
            for part in parts {
                validate_expr(part)?;
            }
        }
        ExprKind::Binary { left, right, .. } => {
            validate_expr(left)?;
            validate_expr(right)?;
        }
        ExprKind::Unary { value, .. } | ExprKind::Env(value) => validate_expr(value)?,
        ExprKind::Call { function, args } => {
            if !is_safe_identifier(function) {
                return Err(CompileError::plain(format!(
                    "unsafe PowerShell function name `{function}`"
                )));
            }
            for argument in args {
                validate_expr(argument)?;
            }
        }
        ExprKind::New { class, args } => {
            if !is_safe_identifier(class) {
                return Err(CompileError::plain(format!(
                    "unsafe PowerShell class name `{class}`"
                )));
            }
            for argument in args {
                validate_expr(argument)?;
            }
        }
        ExprKind::Field { object, class, .. } => {
            if !is_safe_identifier(class) {
                return Err(CompileError::plain(format!(
                    "unsafe PowerShell class name `{class}`"
                )));
            }
            validate_expr(object)?;
        }
        ExprKind::Method {
            object,
            class,
            method,
            args,
        } => {
            if !is_safe_identifier(class) {
                return Err(CompileError::plain(format!(
                    "unsafe PowerShell class name `{class}`"
                )));
            }
            if !is_safe_identifier(method) {
                return Err(CompileError::plain(format!(
                    "unsafe PowerShell method name `{method}`"
                )));
            }
            if let Some(object) = object {
                validate_expr(object)?;
            }
            for argument in args {
                validate_expr(argument)?;
            }
        }
    }
    Ok(())
}