c-shell 0.2.0

An interactive shell for C: type an expression, a statement or a function and see what your real compiler does with it
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
//! Compiling and running one input.
//!
//! A lexical heuristic identifies file-scope-shaped input; the compiler then
//! validates that choice and arbitrates expression versus statement.

use anyhow::{Context, Result};
use std::io::Write as _;
use std::path::PathBuf;
use std::process::Command;
use std::sync::{Arc, Mutex, mpsc};
use std::time::Duration;

use crate::codegen::{self, M_DONE, M_NEW, M_STDIN, M_VAL, Slot};
use crate::errmap;
use crate::lex;
use crate::proc;
use crate::session::Session;

pub struct Outcome {
    pub slot: Slot,
    /// What the new input printed itself.
    pub output: String,
    /// The `Out[n]` value, when the input was an expression.
    pub value: Option<String>,
    /// Anything the new input wrote to stderr.
    pub errors: String,
    /// Live program output already reached the terminal but did not end in
    /// `\n`; the renderer must separate subsequent diagnostics/value/prompt.
    pub streamed_output_needs_newline: bool,
    /// Fresh stdin request lines captured while executing the newest input.
    pub stdin_events: Vec<proc::StdinEvent>,
    /// Compiler warnings, already remapped to input-relative lines.
    pub warnings: String,
    /// Set when the program died abnormally or ran too long.
    pub abnormal: Option<String>,
    /// Set when the input had to be repaired to compile; this is what should
    /// be committed to the session instead of what was typed.
    pub rewritten: Option<String>,
    /// The normal block-scope assembly failed, but entering a nested block
    /// made the compiler accept this declaration as a shadowing rebind.
    pub scoped_rebind: bool,
    /// Existing file-scope item replaced in place, selected by successful
    /// whole-program compilation rather than by parsing a declaration name.
    pub file_replacement: Option<usize>,
    /// The input is a valid expression, but its value category has no printer;
    /// it was evaluated through the silent expression wrapper instead.
    pub unprintable: bool,
}

pub enum Eval {
    Done(Outcome),
    /// Nothing compiled; the text is already remapped to input-relative lines.
    CompileError(String),
}

pub struct Evaluator {
    pub tc: crate::toolchain::Toolchain,
    dir: tempfile::TempDir,
    pub timeout: Duration,
    stream_output: bool,
    allow_program_stdin: bool,
}

impl Evaluator {
    pub fn new(tc: crate::toolchain::Toolchain, timeout: Duration) -> Result<Self> {
        let dir = tempfile::tempdir().context("failed to create temporary directory")?;
        Ok(Evaluator {
            tc,
            dir,
            timeout,
            stream_output: false,
            allow_program_stdin: false,
        })
    }

    fn src_path(&self) -> PathBuf {
        self.dir.path().join("input.c")
    }

    fn exe_path(&self) -> PathBuf {
        self.dir
            .path()
            .join(format!("input{}", std::env::consts::EXE_SUFFIX))
    }

    /// Stream only the newest input's program output as it is produced. Batch
    /// mode leaves this off so transcript ordering remains deterministic.
    pub fn set_stream_output(&mut self, enabled: bool) {
        self.stream_output = enabled;
    }

    /// Whether the newest input may request real stdin. Disabled when stdin is
    /// itself carrying piped C source; enabled for a TTY, `-e`, and scripts.
    pub fn set_program_stdin(&mut self, enabled: bool) {
        self.allow_program_stdin = enabled;
    }

    /// Swap in a different compiler, re-probing what it supports.
    pub fn set_toolchain(&mut self, tc: crate::toolchain::Toolchain) {
        self.tc = tc;
    }

    /// Compile `text`. Either way the compiler's raw diagnostics come back —
    /// on success they are the warnings, which a beginner needs to see.
    ///
    /// The compiler runs under the same deadline as user programs: a hung
    /// compiler (pathological macro expansion, compiler bug) must not freeze
    /// the REPL any more than a hung program may.
    fn compile_text(&self, text: &str) -> std::result::Result<(PathBuf, String), String> {
        let src = self.src_path();
        let exe = self.exe_path();
        if let Err(e) = std::fs::write(&src, text) {
            return Err(format!("cannot write temporary source: {e}"));
        }
        let args = self.tc.compile_args(&src, &exe, self.dir.path());
        let mut cmd = Command::new(&self.tc.path);
        cmd.args(&args);
        let cap = match proc::run_captured(&mut cmd, self.timeout, false) {
            Ok(c) => c,
            Err(e) => return Err(format!("cannot run compiler: {e}")),
        };
        let mut d = String::from_utf8_lossy(&cap.stderr).into_owned();
        d.push_str(&String::from_utf8_lossy(&cap.stdout));
        if cap.stdout_truncated || cap.stderr_truncated {
            d.push_str(&format!(
                "\ncompiler output exceeded {} MiB per stream and was truncated\n",
                proc::MAX_CAPTURE_BYTES / (1024 * 1024)
            ));
        }
        match cap.status {
            Some(st) if st.success() => Ok((exe, d)),
            Some(_) => Err(d),
            None => Err(format!(
                "compiler timed out after {}s and was killed",
                self.timeout.as_secs()
            )),
        }
    }

    /// Query an expression's type through the generated `_Generic` table.
    /// The controlling expression is not evaluated, and the result is never
    /// committed to the replay journal.
    pub fn type_of(&self, session: &Session, input: &str) -> Result<Eval> {
        let prog = codegen::build_type_probe(session, input);
        let src = self.src_path().display().to_string();
        let (start, count) = (prog.new_start_line, prog.new_line_count);
        match self.compile_text(&prog.src) {
            Ok((exe, warns)) => {
                let warnings = errmap::only_new(&errmap::remap(
                    &warns,
                    &src,
                    &prog.src,
                    start,
                    count,
                    &prog.session_line_ranges,
                    prog.wrapped,
                ));
                Ok(Eval::Done(self.run(
                    &exe,
                    Slot::Expr,
                    warnings,
                    prog.uses_stdin_tape,
                    session.stdin_tape(),
                )?))
            }
            Err(diag) => Ok(Eval::CompileError(errmap::drop_stale_warnings(
                &errmap::remap(
                    &diag,
                    &src,
                    &prog.src,
                    start,
                    count,
                    &prog.session_line_ranges,
                    prog.wrapped,
                ),
            ))),
        }
    }

    pub fn eval(&self, session: &Session, input: &str) -> Result<Eval> {
        if function_definition_name(input).as_deref() == Some("main") {
            return Ok(Eval::CompileError(
                "c-shell already provides main(); enter the statements from its body directly and omit the final return"
                    .to_string(),
            ));
        }

        let diag = match self.attempt(session, input)? {
            Ok(o) => return Ok(Eval::Done(o)),
            Err(d) => d,
        };

        // Forgetting the semicolon is the single most common beginner
        // mistake, and the diagnostic for it points at generated scaffolding
        // rather than at anything the user wrote. Retrying costs one compile
        // and only ever on the path that already failed.
        let t = input.trim_end();
        let repairable = !t.ends_with(';') && !t.ends_with('}') && !t.trim_start().starts_with('#');
        if repairable {
            let patched = format!("{t};");
            if let Ok(mut o) = self.attempt(session, &patched)? {
                o.rewritten = Some(patched);
                return Ok(Eval::Done(o));
            }
        }
        Ok(Eval::CompileError(diag))
    }

    /// Try compiler-validated assembly strategies. File-scope-shaped input is
    /// never demoted into `main`: GCC nested functions would make identical
    /// sessions diverge from Clang/MSVC. On a normal failure, candidate
    /// rebinding strategies are accepted only when the whole program compiles.
    fn attempt(
        &self,
        session: &Session,
        input: &str,
    ) -> Result<std::result::Result<Outcome, String>> {
        if looks_file_scope(input) {
            let normal = codegen::build(session, input, Slot::FileScope);
            let reported = match self.try_program(normal, Slot::FileScope, session.stdin_tape())? {
                Ok(o) => return Ok(Ok(o)),
                Err(diag) => diag,
            };

            // Syntax/type errors must not trigger O(session size) retries.
            // Only diagnostics in the compiler's redeclaration family enter
            // replacement arbitration; the candidates themselves are still
            // accepted solely by compiling the complete program.
            if !is_rebinding_diagnostic(&reported) {
                return Ok(Err(reported));
            }

            // Substitute each prior definition in place, newest first. An
            // unrelated removal cannot normally cure a redefinition, while
            // replacing the matching item does; the compiler remains the name
            // and compatibility oracle. Preprocessor directives are not
            // candidates because dropping an #include is not rebinding.
            for index in (0..session.file_items.len()).rev() {
                if session.file_items[index].trim_start().starts_with('#') {
                    continue;
                }
                let prog = codegen::build_file_replacement(session, input, index);
                if let Ok(mut o) = self.try_program(prog, Slot::FileScope, session.stdin_tape())? {
                    o.file_replacement = Some(index);
                    return Ok(Ok(o));
                }
            }
            return Ok(Err(reported));
        }

        let mut reported = String::new();
        let mut expr_reported = None;
        let try_expr = should_try_expr(input);
        let slots: &[Slot] = if try_expr {
            &[Slot::Expr, Slot::Stmt]
        } else {
            &[Slot::Stmt]
        };
        for &slot in slots {
            let normal = codegen::build(session, input, slot);
            match self.try_program(normal, slot, session.stdin_tape())? {
                Ok(o) => return Ok(Ok(o)),
                Err(diag) if slot == Slot::Stmt => {
                    let retry_scoped = is_rebinding_diagnostic(&diag);
                    reported = diag;
                    if retry_scoped {
                        let scoped = codegen::build_scoped_stmt(session, input);
                        if let Ok(mut o) =
                            self.try_program(scoped, Slot::Stmt, session.stdin_tape())?
                        {
                            o.scoped_rebind = true;
                            return Ok(Ok(o));
                        }
                    }
                }
                Err(diag) => expr_reported = Some(diag),
            }
        }

        // The normal Expr wrapper can fail solely because CS_PRINT has no
        // association for this value category. Before missing-semicolon
        // repair turns it into a statement, compile and execute the same text
        // as a silent expression so the UI can explain why there is no value.
        if try_expr {
            let prog = codegen::build_expr_probe(session, input);
            if let Ok(mut o) = self.try_program(prog, Slot::Expr, session.stdin_tape())? {
                o.value = None;
                o.unprintable = true;
                return Ok(Ok(o));
            }
        }
        // Sanitizing statement-fallback fallout can remove its only block for
        // a genuinely incomplete expression (`1 +`). Never return a blank
        // error when the earlier expression compile has a real diagnostic.
        if reported.trim().is_empty()
            && let Some(expr) = expr_reported
        {
            reported = expr;
        }
        Ok(Err(reported))
    }

    fn try_program(
        &self,
        prog: codegen::Program,
        slot: Slot,
        stdin_tape: &[proc::StdinEvent],
    ) -> Result<std::result::Result<Outcome, String>> {
        let src = self.src_path().display().to_string();
        let (start, count) = (prog.new_start_line, prog.new_line_count);
        match self.compile_text(&prog.src) {
            Ok((exe, warns)) => {
                let warnings = errmap::only_new(&errmap::remap(
                    &warns,
                    &src,
                    &prog.src,
                    start,
                    count,
                    &prog.session_line_ranges,
                    prog.wrapped,
                ));
                Ok(Ok(self.run(
                    &exe,
                    slot,
                    warnings,
                    prog.uses_stdin_tape,
                    stdin_tape,
                )?))
            }
            Err(diag) => Ok(Err(errmap::drop_stale_warnings(&errmap::remap(
                &diag,
                &src,
                &prog.src,
                start,
                count,
                &prog.session_line_ranges,
                prog.wrapped,
            )))),
        }
    }

    fn run(
        &self,
        exe: &PathBuf,
        slot: Slot,
        warnings: String,
        uses_stdin_tape: bool,
        stdin_tape: &[proc::StdinEvent],
    ) -> Result<Outcome> {
        let mut cmd = Command::new(exe);
        let taped = uses_stdin_tape || !stdin_tape.is_empty();
        let (request_tx, request_rx) = mpsc::channel();
        let live =
            (self.stream_output || taped).then(|| LiveStreams::new(self.stream_output, request_tx));
        let cap = if taped {
            proc::run_observed_with_stdin_tape(
                &mut cmd,
                self.timeout,
                stdin_tape,
                self.allow_program_stdin,
                request_rx,
                live.as_ref().expect("taped observer").observers(),
            )
        } else if let Some(live) = &live {
            proc::run_observed(
                &mut cmd,
                self.timeout,
                self.allow_program_stdin,
                live.observers(),
            )
        } else {
            proc::run_captured(&mut cmd, self.timeout, self.allow_program_stdin)
        }
        .with_context(|| format!("failed to start {}", exe.display()))?;
        if let Some(live) = &live {
            live.finish();
        }

        let out = String::from_utf8_lossy(&cap.stdout).into_owned();
        let err = String::from_utf8_lossy(&cap.stderr).into_owned();
        let out_parts = split_new(&out, true);
        let err_parts = split_new(&err, false);

        let abnormal = match cap.status {
            None => Some(format!(
                "killed after {}s (possible infinite loop)",
                self.timeout.as_secs()
            )),
            Some(st) => describe_abnormal(&st),
        }
        .or_else(|| {
            (cap.stdout_truncated || cap.stderr_truncated).then(|| {
                format!(
                    "program output exceeded {} MiB per stream and was truncated",
                    proc::MAX_CAPTURE_BYTES / (1024 * 1024)
                )
            })
        })
        .or_else(|| {
            cap.stdin_diverged.then(|| {
                "stdin tape diverged while replaying retained input; use %undo or %reset"
                    .to_string()
            })
        })
        .or_else(|| {
            (!out_parts.done || !err_parts.done)
                .then(|| "program exited before the input completed".to_string())
        });

        let streamed_output_needs_newline = live
            .as_ref()
            .is_some_and(|live| live.terminal_needs_newline());

        Ok(Outcome {
            slot,
            output: if self.stream_output {
                String::new()
            } else {
                out_parts.output
            },
            value: out_parts.value.filter(|_| {
                slot == Slot::Expr
                    && out_parts.done
                    && err_parts.done
                    && !cap.stdout_truncated
                    && !cap.stderr_truncated
            }),
            errors: if self.stream_output {
                String::new()
            } else {
                err_parts.output
            },
            streamed_output_needs_newline,
            stdin_events: cap.stdin_recorded,
            warnings,
            abnormal,
            rewritten: None,
            scoped_rebind: false,
            file_replacement: None,
            unprintable: false,
        })
    }
}

struct SplitOutput {
    output: String,
    value: Option<String>,
    done: bool,
}

/// Keep only what the newest input produced, strip the completion marker and
/// separate the printed value. Missing M_DONE means even exit status 0 is not
/// enough to commit (`exit(0)` and a top-level `return` are the classic cases).
fn split_new(s: &str, has_value: bool) -> SplitOutput {
    let Some(start) = s.rfind(M_NEW) else {
        return SplitOutput {
            output: s.to_string(),
            value: None,
            done: false,
        };
    };
    let tail = &s[start + M_NEW.len()..];
    let (body, done) = match tail.rfind(M_DONE) {
        Some(i) => (&tail[..i], true),
        None => (tail, false),
    };
    let body = body.replace(M_STDIN, "");
    if has_value && let Some(i) = body.rfind(M_VAL) {
        return SplitOutput {
            output: body[..i].to_string(),
            value: Some(
                body[i + M_VAL.len()..]
                    .trim_end_matches(['\r', '\n'])
                    .to_string(),
            ),
            done,
        };
    }
    SplitOutput {
        output: body,
        value: None,
        done,
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum LiveState {
    BeforeInput,
    Output,
    Value,
    Done,
}

/// Incrementally strips replay/protocol bytes and returns only bytes that the
/// newest input itself wrote. Markers may straddle arbitrary pipe chunks.
struct LiveFilter {
    state: LiveState,
    stdout: bool,
    pending: Vec<u8>,
    visible_any: bool,
    visible_ends_in_newline: bool,
    stdin_requests: Vec<proc::StdinRequest>,
}

impl LiveFilter {
    fn new(stdout: bool) -> Self {
        Self {
            state: LiveState::BeforeInput,
            stdout,
            pending: Vec::new(),
            visible_any: false,
            visible_ends_in_newline: false,
            stdin_requests: Vec::new(),
        }
    }

    fn feed(&mut self, chunk: &[u8]) -> Vec<u8> {
        self.pending.extend_from_slice(chunk);
        let mut visible = Vec::new();
        loop {
            match self.state {
                LiveState::BeforeInput => {
                    let new = find_bytes(&self.pending, M_NEW.as_bytes());
                    let request = (!self.stdout)
                        .then(|| find_bytes(&self.pending, M_STDIN.as_bytes()))
                        .flatten();
                    if request.is_some_and(|r| new.is_none_or(|n| r < n)) {
                        let i = request.expect("checked request");
                        self.pending.drain(..i + M_STDIN.len());
                        self.stdin_requests.push(proc::StdinRequest::Replay);
                    } else if let Some(i) = new {
                        self.pending.drain(..i + M_NEW.len());
                        self.state = LiveState::Output;
                    } else {
                        let markers: &[&[u8]] = if self.stdout {
                            &[M_NEW.as_bytes()]
                        } else {
                            &[M_NEW.as_bytes(), M_STDIN.as_bytes()]
                        };
                        retain_marker_prefix(&mut self.pending, markers);
                        break;
                    }
                }
                LiveState::Output => {
                    let value = self
                        .stdout
                        .then(|| find_bytes(&self.pending, M_VAL.as_bytes()))
                        .flatten();
                    let done = find_bytes(&self.pending, M_DONE.as_bytes());
                    let request = (!self.stdout)
                        .then(|| find_bytes(&self.pending, M_STDIN.as_bytes()))
                        .flatten();
                    let mut next = Vec::new();
                    if let Some(i) = value {
                        next.push((i, M_VAL.len(), Some(LiveState::Value)));
                    }
                    if let Some(i) = done {
                        next.push((i, M_DONE.len(), Some(LiveState::Done)));
                    }
                    if let Some(i) = request {
                        next.push((i, M_STDIN.len(), None));
                    }
                    if let Some((i, marker_len, state)) =
                        next.into_iter().min_by_key(|(i, _, _)| *i)
                    {
                        visible.extend_from_slice(&self.pending[..i]);
                        self.pending.drain(..i + marker_len);
                        if let Some(state) = state {
                            self.state = state;
                        } else {
                            self.stdin_requests.push(proc::StdinRequest::Current);
                        }
                    } else {
                        let markers: &[&[u8]] = if self.stdout {
                            &[M_VAL.as_bytes(), M_DONE.as_bytes()]
                        } else {
                            &[M_DONE.as_bytes(), M_STDIN.as_bytes()]
                        };
                        let keep = trailing_marker_prefix(&self.pending, markers);
                        let safe = self.pending.len() - keep;
                        visible.extend_from_slice(&self.pending[..safe]);
                        self.pending.drain(..safe);
                        break;
                    }
                }
                LiveState::Value => {
                    if let Some(i) = find_bytes(&self.pending, M_DONE.as_bytes()) {
                        self.pending.drain(..i + M_DONE.len());
                        self.state = LiveState::Done;
                    } else {
                        retain_marker_prefix(&mut self.pending, &[M_DONE.as_bytes()]);
                        break;
                    }
                }
                LiveState::Done => {
                    self.pending.clear();
                    break;
                }
            }
        }
        self.record_visible(&visible);
        visible
    }

    fn take_stdin_requests(&mut self) -> Vec<proc::StdinRequest> {
        std::mem::take(&mut self.stdin_requests)
    }

    fn finish(&mut self) -> Vec<u8> {
        let visible = if self.state == LiveState::Output {
            std::mem::take(&mut self.pending)
        } else {
            self.pending.clear();
            Vec::new()
        };
        self.record_visible(&visible);
        visible
    }

    fn record_visible(&mut self, visible: &[u8]) {
        if let Some(last) = visible.last() {
            self.visible_any = true;
            self.visible_ends_in_newline = *last == b'\n';
        }
    }
}

fn find_bytes(haystack: &[u8], needle: &[u8]) -> Option<usize> {
    haystack.windows(needle.len()).position(|w| w == needle)
}

fn trailing_marker_prefix(bytes: &[u8], markers: &[&[u8]]) -> usize {
    markers
        .iter()
        .map(|marker| {
            let max = bytes.len().min(marker.len().saturating_sub(1));
            (1..=max)
                .rev()
                .find(|&n| bytes.ends_with(&marker[..n]))
                .unwrap_or(0)
        })
        .max()
        .unwrap_or(0)
}

fn retain_marker_prefix(bytes: &mut Vec<u8>, markers: &[&[u8]]) {
    let keep = trailing_marker_prefix(bytes, markers);
    bytes.drain(..bytes.len() - keep);
}

#[derive(Default)]
struct TerminalVisibility {
    visible_any: bool,
    visible_ends_in_newline: bool,
}

impl TerminalVisibility {
    fn record(&mut self, visible: &[u8]) {
        if let Some(last) = visible.last() {
            self.visible_any = true;
            self.visible_ends_in_newline = *last == b'\n';
        }
    }

    fn needs_newline(&self) -> bool {
        self.visible_any && !self.visible_ends_in_newline
    }
}

struct LiveStreams {
    stdout: Arc<Mutex<LiveFilter>>,
    stderr: Arc<Mutex<LiveFilter>>,
    terminal: Arc<Mutex<TerminalVisibility>>,
    stream_visible: bool,
    stdin_requests: mpsc::Sender<proc::StdinRequest>,
}

impl LiveStreams {
    fn new(stream_visible: bool, stdin_requests: mpsc::Sender<proc::StdinRequest>) -> Self {
        Self {
            stdout: Arc::new(Mutex::new(LiveFilter::new(true))),
            stderr: Arc::new(Mutex::new(LiveFilter::new(false))),
            terminal: Arc::new(Mutex::new(TerminalVisibility::default())),
            stream_visible,
            stdin_requests,
        }
    }

    fn observers(&self) -> proc::Observers {
        let stdout = Arc::clone(&self.stdout);
        let stderr = Arc::clone(&self.stderr);
        let stdout_terminal = Arc::clone(&self.terminal);
        let stderr_terminal = Arc::clone(&self.terminal);
        let stdout_requests = self.stdin_requests.clone();
        let stderr_requests = self.stdin_requests.clone();
        let stream_stdout = self.stream_visible;
        let stream_stderr = self.stream_visible;
        proc::Observers {
            stdout: Arc::new(move |chunk| {
                let (visible, requests) = {
                    let mut filter = stdout.lock().expect("stdout filter");
                    let visible = filter.feed(chunk);
                    (visible, filter.take_stdin_requests())
                };
                for request in requests {
                    let _ = stdout_requests.send(request);
                }
                if stream_stdout && !visible.is_empty() {
                    // Serialize the two stream writers so this state records
                    // the actual last byte placed on the shared terminal.
                    let mut terminal = stdout_terminal.lock().expect("terminal visibility");
                    let mut out = std::io::stdout().lock();
                    let _ = out.write_all(&visible);
                    let _ = out.flush();
                    terminal.record(&visible);
                }
            }),
            stderr: Arc::new(move |chunk| {
                let (visible, requests) = {
                    let mut filter = stderr.lock().expect("stderr filter");
                    let visible = filter.feed(chunk);
                    (visible, filter.take_stdin_requests())
                };
                for request in requests {
                    let _ = stderr_requests.send(request);
                }
                if stream_stderr && !visible.is_empty() {
                    let mut terminal = stderr_terminal.lock().expect("terminal visibility");
                    let mut err = std::io::stderr().lock();
                    let _ = err.write_all(&visible);
                    let _ = err.flush();
                    terminal.record(&visible);
                }
            }),
        }
    }

    fn finish(&self) {
        let out_tail = self.stdout.lock().expect("stdout filter").finish();
        if self.stream_visible && !out_tail.is_empty() {
            let mut terminal = self.terminal.lock().expect("terminal visibility");
            let mut out = std::io::stdout().lock();
            let _ = out.write_all(&out_tail);
            let _ = out.flush();
            terminal.record(&out_tail);
        }
        let err_tail = self.stderr.lock().expect("stderr filter").finish();
        if self.stream_visible && !err_tail.is_empty() {
            let mut terminal = self.terminal.lock().expect("terminal visibility");
            let mut err = std::io::stderr().lock();
            let _ = err.write_all(&err_tail);
            let _ = err.flush();
            terminal.record(&err_tail);
        }
    }

    fn terminal_needs_newline(&self) -> bool {
        self.terminal
            .lock()
            .expect("terminal visibility")
            .needs_newline()
    }
}

#[cfg(unix)]
fn describe_abnormal(st: &std::process::ExitStatus) -> Option<String> {
    use std::os::unix::process::ExitStatusExt;
    let sig = st.signal()?;
    Some(match sig {
        11 => "program crashed: segmentation fault (SIGSEGV) — \
               usually a NULL/wild pointer dereference or an out-of-bounds index"
            .into(),
        6 => "program aborted (SIGABRT) — \
              usually a failed assert, or heap corruption caught by the C library"
            .into(),
        8 => "arithmetic error (SIGFPE) — usually integer division by zero".into(),
        4 => "illegal instruction (SIGILL)".into(),
        7 | 10 => "bus error (SIGBUS) — usually a misaligned memory access".into(),
        _ => format!("program terminated by signal {sig}"),
    })
}

#[cfg(windows)]
fn describe_abnormal(st: &std::process::ExitStatus) -> Option<String> {
    // Windows has no signals; a fatal fault surfaces as an NTSTATUS exit code.
    let code = st.code()? as u32;
    Some(match code {
        0xC0000005 => "program crashed: access violation — \
                       usually a NULL/wild pointer dereference or an out-of-bounds index"
            .into(),
        0xC0000094 => "arithmetic error: integer division by zero".into(),
        0xC000001D => "illegal instruction".into(),
        0xC00000FD => "stack overflow — usually runaway recursion or a huge stack array".into(),
        0xC0000409 => "stack buffer overrun detected".into(),
        _ => return None,
    })
}

/// Diagnostics that mean "this name already denotes something here".
/// GNU/Clang spellings are textual; MSVC diagnostic codes remain stable even
/// when its prose is localized. A positive match only enables a retry — the
/// alternate assembly still has to compile and run before it can be committed.
fn is_rebinding_diagnostic(diag: &str) -> bool {
    let lower = diag.to_ascii_lowercase();
    [
        "redefinition",
        "redeclaration",
        "redeclared",
        "conflicting types for",
        "already has a body",
        "c2011",
        "c2084",
        "c2086",
        "c2365",
        "c2371",
        "c2373",
        "c2374",
        "c2375",
        "c2556",
    ]
    .iter()
    .any(|needle| lower.contains(needle))
}

/// Whether expression classification can possibly succeed.
///
/// A top-level trailing semicolon makes the `CS_PRINT((input))` wrapper
/// syntactically impossible, so statement-shaped input takes one compiler
/// process instead of predictably failing an expression compile first. A
/// trailing `}` normally has the same property, except for C compound
/// literals such as `(int){1}` or `x = (Point){1, 2}`.
fn should_try_expr(input: &str) -> bool {
    let scan = lex::scan(input);
    let Some(last) = input
        .as_bytes()
        .iter()
        .enumerate()
        .rev()
        .find(|(i, byte)| scan.code[*i] && !byte.is_ascii_whitespace())
        .map(|(i, _)| i)
    else {
        return false;
    };
    match input.as_bytes()[last] {
        b';' => false,
        b'}' => ends_in_possible_compound_literal(input, &scan.code, last),
        _ => true,
    }
}

fn ends_in_possible_compound_literal(input: &str, code: &[bool], close: usize) -> bool {
    let bytes = input.as_bytes();
    let mut depth = 0usize;
    let mut open = None;
    for i in (0..=close).rev() {
        if !code[i] {
            continue;
        }
        match bytes[i] {
            b'}' => depth += 1,
            b'{' => {
                depth -= 1;
                if depth == 0 {
                    open = Some(i);
                    break;
                }
            }
            _ => {}
        }
    }
    let Some(open) = open else { return true };
    let Some(before) = (0..open)
        .rev()
        .find(|&i| code[i] && !bytes[i].is_ascii_whitespace())
    else {
        return false;
    };
    if bytes[before] != b')' {
        return false;
    }

    // `if (x) { ... }` has the same `) {` boundary as a compound literal.
    // Clear control-flow prefixes are statements; ambiguous forms keep the
    // expression trial so classification can never reject valid C merely to
    // save a process launch.
    !lex::identifiers(input).first().is_some_and(|word| {
        matches!(
            word.as_str(),
            "if" | "for" | "while" | "switch" | "do" | "else" | "case"
        )
    })
}

/// Does this input have to live outside `main`?
///
/// This lexical routing is exclusive: once input has file-scope shape it is
/// never retried as a statement, because GCC might accept a nested function.
fn looks_file_scope(input: &str) -> bool {
    let t = input.trim_start();
    if t.starts_with('#') {
        return true;
    }
    let first: String = t
        .chars()
        .take_while(|c| c.is_alphanumeric() || *c == '_')
        .collect();
    // `if (x) { ... }` also contains `) {`, so control flow is excluded before
    // the function-definition test below.
    if matches!(
        first.as_str(),
        "if" | "for"
            | "while"
            | "switch"
            | "do"
            | "else"
            | "return"
            | "case"
            | "goto"
            | "break"
            | "continue"
            | "sizeof"
    ) {
        return false;
    }
    if first == "typedef" {
        return true;
    }
    // A type definition, as opposed to a variable of that type: hoisting it
    // keeps the type usable from functions defined later. The two are told
    // apart by what follows the tag — `struct P {` defines, `struct P p`
    // declares.
    if matches!(first.as_str(), "struct" | "union" | "enum") {
        let after_kw = t[first.len()..].trim_start();
        let tag: String = after_kw
            .chars()
            .take_while(|c| c.is_alphanumeric() || *c == '_')
            .collect();
        if after_kw[tag.len()..].trim_start().starts_with('{') {
            return true;
        }
        return false;
    }
    !first.is_empty() && function_definition_name(input).is_some()
}

/// Return the simple function name whose parameter list meets a top-level
/// body brace. Merely spotting `) {` is insufficient: compound literals such
/// as `Point p = (Point){1, 2}` have the same byte pattern.
fn function_definition_name(input: &str) -> Option<String> {
    let sc = lex::scan(input);
    let b = input.as_bytes();
    let mut parens = 0i32;
    let mut brackets = 0i32;
    let mut brace = None;
    for (i, &byte) in b.iter().enumerate() {
        if !sc.code[i] {
            continue;
        }
        match byte {
            b'(' => parens += 1,
            b')' => parens -= 1,
            b'[' => brackets += 1,
            b']' => brackets -= 1,
            b'=' if parens == 0 && brackets == 0 => return None,
            b'{' if parens == 0 && brackets == 0 => {
                brace = Some(i);
                break;
            }
            // Braces while parentheses remain open can belong to a struct in
            // a parameter list (or to an expression); only a later top-level
            // brace can be the function body.
            b'{' => {}
            _ => {}
        }
    }
    let brace = brace?;
    let close = (0..brace)
        .rev()
        .find(|&i| sc.code[i] && !b[i].is_ascii_whitespace())?;
    if b[close] != b')' {
        return None;
    }

    // Find that closing paren's mate and require a declarator-like token just
    // before it. This rejects `(Type){...}` and `cond ? (Type){...}`.
    let mut depth = 0i32;
    let mut open = None;
    for i in (0..=close).rev() {
        if !sc.code[i] {
            continue;
        }
        match b[i] {
            b')' => depth += 1,
            b'(' => {
                depth -= 1;
                if depth == 0 {
                    open = Some(i);
                    break;
                }
            }
            _ => {}
        }
    }
    let open = open?;
    let before = (0..open)
        .rev()
        .find(|&i| sc.code[i] && !b[i].is_ascii_whitespace())?;
    if b[before] == b')' {
        // Parenthesized declarator: `int (main)(void) { ... }`.
        let mut depth = 0i32;
        let mut inner_open = None;
        for i in (0..=before).rev() {
            if !sc.code[i] {
                continue;
            }
            match b[i] {
                b')' => depth += 1,
                b'(' => {
                    depth -= 1;
                    if depth == 0 {
                        inner_open = Some(i);
                        break;
                    }
                }
                _ => {}
            }
        }
        let inner_open = inner_open?;
        return identifier_between(input, &sc.code, inner_open + 1, before);
    }
    identifier_ending_at(input, &sc.code, before)
}

fn identifier_ending_at(input: &str, code: &[bool], end: usize) -> Option<String> {
    let b = input.as_bytes();
    if !(b[end] == b'_' || b[end].is_ascii_alphanumeric()) {
        return None;
    }
    let mut start = end;
    while start > 0
        && code[start - 1]
        && (b[start - 1] == b'_' || b[start - 1].is_ascii_alphanumeric())
    {
        start -= 1;
    }
    (!b[start].is_ascii_digit()).then(|| input[start..=end].to_string())
}

fn identifier_between(input: &str, code: &[bool], start: usize, end: usize) -> Option<String> {
    let b = input.as_bytes();
    let first = (start..end).find(|&i| code[i] && !b[i].is_ascii_whitespace())?;
    let last = (first..end)
        .rev()
        .find(|&i| code[i] && !b[i].is_ascii_whitespace())?;
    let ident = identifier_ending_at(input, code, last)?;
    let ident_start = last + 1 - ident.len();
    (ident_start == first).then_some(ident)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn skips_impossible_expression_trials_without_losing_compound_literals() {
        assert!(!should_try_expr("int value = 1;"));
        assert!(!should_try_expr("value++; // retained statement"));
        assert!(!should_try_expr("if (value) { value--; }"));
        assert!(!should_try_expr("{ value++; }"));
        assert!(should_try_expr("value + 1"));
        assert!(should_try_expr("(int){ 7 }"));
        assert!(should_try_expr("value = (struct Box){ 7 }"));
    }

    #[test]
    fn recognizes_portable_rebinding_diagnostics() {
        assert!(is_rebinding_diagnostic("error: redefinition of 'f'"));
        assert!(is_rebinding_diagnostic("error: conflicting types for 'x'"));
        assert!(is_rebinding_diagnostic(
            "error C2084: function 'f' already has a body"
        ));
        assert!(!is_rebinding_diagnostic("error: expected expression"));
    }

    #[test]
    fn recognizes_main_definitions_without_matching_similar_expressions() {
        assert_eq!(
            function_definition_name("int main(void) { return 0; }").as_deref(),
            Some("main")
        );
        assert_eq!(
            function_definition_name("int (main)(int argc, char **argv) { return argc; }")
                .as_deref(),
            Some("main")
        );
        assert_eq!(
            function_definition_name("int domain(void) { return 1; }").as_deref(),
            Some("domain")
        );
        assert_eq!(function_definition_name("Point p = (Point){1, 2};"), None);
    }

    #[test]
    fn routes_definitions_to_file_scope() {
        assert!(looks_file_scope("int add(int a, int b) { return a + b; }"));
        assert!(looks_file_scope(
            "int get(struct Local { int x; } v) { return v.x; }"
        ));
        assert!(looks_file_scope("#include <time.h>"));
        assert!(looks_file_scope("typedef unsigned long ulong;"));
        assert!(looks_file_scope("struct P { int x; int y; };"));
    }

    #[test]
    fn keeps_statements_in_main() {
        assert!(!looks_file_scope("if (x > 0) { puts(\"hi\"); }"));
        assert!(!looks_file_scope("for (int i = 0; i < 3; i++) { }"));
        assert!(!looks_file_scope("(struct P){ 1, 2 }"));
        assert!(!looks_file_scope("Point p = (Point){ 1, 2 };"));
        assert!(!looks_file_scope("flag ? (Point){ 1, 2 } : other"));
        assert!(!looks_file_scope("int x = 41;"));
        assert!(!looks_file_scope("struct P p = {1, 2};"));
        assert!(!looks_file_scope("x + 1"));
    }

    #[test]
    fn splits_on_markers_and_requires_completion() {
        let s = format!("old{M_NEW}printed{M_VAL}42\n{M_DONE}");
        let got = split_new(&s, true);
        assert_eq!(got.output, "printed");
        assert_eq!(got.value.as_deref(), Some("42"));
        assert!(got.done);
    }

    #[test]
    fn missing_start_or_done_is_incomplete() {
        let no_start = split_new("crashed early", true);
        assert_eq!(no_start.output, "crashed early");
        assert!(!no_start.done);

        let no_done = split_new(&format!("{M_NEW}before exit"), true);
        assert_eq!(no_done.output, "before exit");
        assert!(!no_done.done);
    }

    #[test]
    fn live_filter_handles_markers_split_across_chunks() {
        let mut f = LiveFilter::new(true);
        let wire = format!("replayed{M_NEW}hello{M_VAL}42\n{M_DONE}");
        let mut visible = Vec::new();
        for chunk in wire.as_bytes().chunks(3) {
            visible.extend(f.feed(chunk));
        }
        visible.extend(f.finish());
        assert_eq!(visible, b"hello");
        assert_eq!(f.state, LiveState::Done);
        assert!(f.visible_any && !f.visible_ends_in_newline);
    }

    #[test]
    fn live_filter_reports_historical_and_current_stdin_requests() {
        let mut filter = LiveFilter::new(false);
        let wire = format!("old{M_STDIN}{M_NEW}prompt: {M_STDIN}{M_DONE}");
        let mut visible = Vec::new();
        let mut requests = Vec::new();
        for chunk in wire.as_bytes().chunks(3) {
            visible.extend(filter.feed(chunk));
            requests.extend(filter.take_stdin_requests());
        }
        assert_eq!(visible, b"prompt: ");
        assert_eq!(
            requests,
            [proc::StdinRequest::Replay, proc::StdinRequest::Current]
        );
    }

    #[test]
    fn terminal_newline_state_follows_the_last_interleaved_stream_write() {
        let mut terminal = TerminalVisibility::default();
        terminal.record(b"stdout without newline");
        assert!(terminal.needs_newline());
        terminal.record(b"stderr finishes the terminal line\n");
        assert!(!terminal.needs_newline());
        terminal.record(b"partial again");
        assert!(terminal.needs_newline());
    }

    #[test]
    fn stderr_live_filter_streams_until_done() {
        let mut f = LiveFilter::new(false);
        let wire = format!("old{M_NEW}warning text\n{M_DONE}");
        assert_eq!(f.feed(wire.as_bytes()), b"warning text\n");
        assert_eq!(f.state, LiveState::Done);
        assert!(f.visible_any && f.visible_ends_in_newline);
    }
}