yosh 0.2.7

A POSIX-compliant shell implemented in Rust
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
use std::ffi::CString;
use std::io::Write;

use crate::env::{FlowControl, ShellEnv, TrapAction};
use crate::error::{RuntimeErrorKind, ShellError};
use crate::exec::Executor;
use crate::parser::word::is_valid_name;

pub fn exec_special_builtin(name: &str, args: &[String], executor: &mut Executor) -> i32 {
    let result = match name {
        ":" => Ok(0),
        "exit" => builtin_exit(args, executor),
        "export" => builtin_export(args, &mut executor.env),
        "unset" => builtin_unset(args, &mut executor.env),
        "readonly" => builtin_readonly(args, &mut executor.env),
        "return" => builtin_return(args, &mut executor.env),
        "break" => builtin_break(args, &mut executor.env),
        "continue" => builtin_continue(args, &mut executor.env),
        "set" => {
            let was_monitor = executor.env.mode.options.monitor;
            let ret = match builtin_set(args, &mut executor.env) {
                Ok(s) => s,
                Err(e) => {
                    eprintln!("{}", e);
                    return e.exit_code();
                }
            };
            let is_monitor = executor.env.mode.options.monitor;
            if was_monitor && !is_monitor {
                crate::signal::reset_job_control_signals();
            } else if !was_monitor && is_monitor {
                crate::signal::init_job_control_signals();
            }
            return ret;
        }
        "eval" => builtin_eval(args, executor),
        "exec" => builtin_exec(args, &mut executor.env),
        "trap" => builtin_trap(args, &mut executor.env),
        "." => builtin_source(args, executor),
        "shift" => builtin_shift(args, &mut executor.env),
        "times" => builtin_times(args),
        "fc" => builtin_fc(args, executor),
        _ => Err(ShellError::runtime(
            RuntimeErrorKind::InvalidArgument,
            format!("{}: not a special builtin", name),
        )),
    };
    match result {
        Ok(status) => status,
        Err(e) => {
            eprintln!("{}", e);
            e.exit_code()
        }
    }
}

// ---------------------------------------------------------------------------
// Existing implementations (moved from mod.rs)
// ---------------------------------------------------------------------------

fn builtin_exit(args: &[String], executor: &mut Executor) -> Result<i32, ShellError> {
    let code = if args.is_empty() {
        executor.env.exec.last_exit_status
    } else {
        match args[0].parse::<i32>() {
            Ok(n) => n & 0xFF,
            Err(_) => {
                return Err(ShellError::runtime(
                    RuntimeErrorKind::InvalidArgument,
                    format!("exit: {}: numeric argument required", args[0]),
                ));
            }
        }
    };
    executor.process_pending_signals();
    executor.execute_exit_trap();
    if executor.env.mode.is_interactive {
        executor.exit_requested = Some(code);
        Ok(code)
    } else {
        std::process::exit(code);
    }
}

fn builtin_export(args: &[String], env: &mut ShellEnv) -> Result<i32, ShellError> {
    if args.is_empty() || args[0] == "-p" {
        // Print all exported variables in POSIX re-input format
        let mut exported: Vec<(String, String)> = env.vars.environ().to_vec();
        exported.sort_by(|a, b| a.0.cmp(&b.0));
        for (name, value) in exported {
            println!("export {}=\"{}\"", name, value);
        }
        return Ok(0);
    }

    let mut status = 0;
    for arg in args {
        let name = match arg.find('=') {
            Some(pos) => &arg[..pos],
            None => arg.as_str(),
        };
        if !is_valid_name(name) {
            eprintln!("yosh: export: `{}': not a valid identifier", name);
            status = 1;
            continue;
        }
        if let Some(pos) = arg.find('=') {
            let raw_value = &arg[pos + 1..];
            if let Err(e) = env.assign_var(name, raw_value) {
                eprintln!("yosh: export: {}", e);
                status = 1;
                continue;
            }
            env.vars.export(name);
        } else {
            env.vars.export(name);
        }
    }
    Ok(status)
}

fn builtin_unset(args: &[String], env: &mut ShellEnv) -> Result<i32, ShellError> {
    // POSIX §2.14.18: unset [-fv] name...
    // -f removes function definitions; -v (default) removes variables.
    // Combining -f and -v is rejected with status 2.
    let mut mode_f = false;
    let mut mode_v = false;
    let mut idx = 0;
    while idx < args.len() {
        let arg = args[idx].as_str();
        if arg == "--" {
            idx += 1;
            break;
        }
        if arg == "-" || !arg.starts_with('-') || arg.len() == 1 {
            break;
        }
        for ch in arg[1..].chars() {
            match ch {
                'f' => mode_f = true,
                'v' => mode_v = true,
                _ => {
                    eprintln!("yosh: unset: -{}: invalid option", ch);
                    return Ok(2);
                }
            }
        }
        idx += 1;
    }
    if mode_f && mode_v {
        eprintln!("yosh: unset: cannot simultaneously unset a function and a variable");
        return Ok(2);
    }
    let unset_functions = mode_f;

    let mut status = 0;
    for name in &args[idx..] {
        if !is_valid_name(name) {
            eprintln!("yosh: unset: `{}': not a valid identifier", name);
            status = 1;
            continue;
        }
        if unset_functions {
            env.functions.remove(name);
        } else if let Err(e) = env.unset_var(name) {
            eprintln!("yosh: unset: {}", e);
            status = 1;
        }
    }
    Ok(status)
}

fn builtin_readonly(args: &[String], env: &mut ShellEnv) -> Result<i32, ShellError> {
    // POSIX §2.14.11: "When invoked with no arguments or with the -p
    // option, readonly shall write...". bash/dash treat -p as a listing
    // trigger that suppresses any operand processing.
    if args.is_empty() || args.iter().any(|a| a == "-p") {
        let readonly_vars: Vec<(String, String)> = env
            .vars
            .vars_iter()
            .filter(|(_, v)| v.readonly)
            .map(|(k, v)| (k.to_string(), v.value.clone()))
            .collect();
        let mut sorted = readonly_vars;
        sorted.sort_by(|a, b| a.0.cmp(&b.0));
        for (name, value) in sorted {
            println!("readonly {}={}", name, value);
        }
        return Ok(0);
    }

    let mut status = 0;
    for arg in args {
        let name = match arg.find('=') {
            Some(pos) => &arg[..pos],
            None => arg.as_str(),
        };
        if !is_valid_name(name) {
            eprintln!("yosh: readonly: `{}': not a valid identifier", name);
            status = 1;
            continue;
        }
        if let Some(pos) = arg.find('=') {
            let raw_value = &arg[pos + 1..];
            if let Err(e) = env.vars.set(name, raw_value) {
                eprintln!("yosh: readonly: {}", e);
                status = 1;
                continue;
            }
            env.vars.set_readonly(name);
        } else {
            env.vars.set_readonly(name);
        }
    }
    Ok(status)
}

fn builtin_return(args: &[String], env: &mut ShellEnv) -> Result<i32, ShellError> {
    if env.vars.scope_depth() <= 1 && !env.mode.in_dot_script {
        return Err(ShellError::runtime(
            RuntimeErrorKind::IoError,
            "return: can only return from a function or sourced script".to_string(),
        ));
    }
    let code = if args.is_empty() {
        env.exec.last_exit_status & 0xFF
    } else {
        match args[0].parse::<i32>() {
            Ok(n) => n & 0xFF,
            Err(_) => {
                return Err(ShellError::runtime(
                    RuntimeErrorKind::InvalidArgument,
                    format!("return: {}: numeric argument required", args[0]),
                ));
            }
        }
    };
    env.exec.flow_control = Some(FlowControl::Return(code));
    Ok(code)
}

fn builtin_break(args: &[String], env: &mut ShellEnv) -> Result<i32, ShellError> {
    if env.exec.loop_depth == 0 {
        eprintln!("yosh: break: only meaningful in a `for', `while', or `until' loop");
        return Ok(1);
    }
    let n = if args.is_empty() {
        1
    } else {
        match args[0].parse::<usize>() {
            Ok(0) => {
                return Err(ShellError::runtime(
                    RuntimeErrorKind::InvalidArgument,
                    "break: loop count must be > 0".to_string(),
                ));
            }
            Ok(n) => n,
            Err(_) => {
                return Err(ShellError::runtime(
                    RuntimeErrorKind::InvalidArgument,
                    format!("break: {}: numeric argument required", args[0]),
                ));
            }
        }
    };
    let clamped = n.min(env.exec.loop_depth);
    env.exec.flow_control = Some(FlowControl::Break(clamped));
    Ok(0)
}

fn builtin_continue(args: &[String], env: &mut ShellEnv) -> Result<i32, ShellError> {
    if env.exec.loop_depth == 0 {
        eprintln!("yosh: continue: only meaningful in a `for', `while', or `until' loop");
        return Ok(1);
    }
    let n = if args.is_empty() {
        1
    } else {
        match args[0].parse::<usize>() {
            Ok(0) => {
                return Err(ShellError::runtime(
                    RuntimeErrorKind::InvalidArgument,
                    "continue: loop count must be > 0".to_string(),
                ));
            }
            Ok(n) => n,
            Err(_) => {
                return Err(ShellError::runtime(
                    RuntimeErrorKind::InvalidArgument,
                    format!("continue: {}: numeric argument required", args[0]),
                ));
            }
        }
    };
    let clamped = n.min(env.exec.loop_depth);
    env.exec.flow_control = Some(FlowControl::Continue(clamped));
    Ok(0)
}

// ---------------------------------------------------------------------------
// Implementations for new builtins
// ---------------------------------------------------------------------------

fn builtin_set(args: &[String], env: &mut ShellEnv) -> Result<i32, ShellError> {
    if args.is_empty() {
        // Display all variables sorted
        let mut vars: Vec<(String, String)> = env
            .vars
            .vars_iter()
            .map(|(k, v)| (k.to_string(), v.value.clone()))
            .collect();
        vars.sort_by(|a, b| a.0.cmp(&b.0));
        for (name, value) in vars {
            println!("{}={}", name, value);
        }
        return Ok(0);
    }

    let mut i = 0;
    while i < args.len() {
        let arg = &args[i];
        if arg == "--" {
            env.vars.set_positional_params(args[i + 1..].to_vec());
            return Ok(0);
        }
        if arg == "-" {
            env.mode.options.xtrace = false;
            env.mode.options.verbose = false;
            if i + 1 < args.len() {
                env.vars.set_positional_params(args[i + 1..].to_vec());
            }
            return Ok(0);
        }
        if arg == "-o" || arg == "+o" {
            let on = arg.starts_with('-');
            i += 1;
            if i >= args.len() {
                if on {
                    env.mode.options.display_all();
                } else {
                    env.mode.options.display_restorable();
                }
                return Ok(0);
            }
            if let Err(e) = env.mode.options.set_by_name(&args[i], on) {
                return Err(ShellError::runtime(RuntimeErrorKind::InvalidOption, e));
            }
            i += 1;
            continue;
        }
        if arg.starts_with('-') || arg.starts_with('+') {
            let on = arg.starts_with('-');
            for c in arg[1..].chars() {
                if let Err(e) = env.mode.options.set_by_char(c, on) {
                    return Err(ShellError::runtime(RuntimeErrorKind::InvalidOption, e));
                }
            }
            i += 1;
            continue;
        }
        // Remaining args are positional params
        env.vars.set_positional_params(args[i..].to_vec());
        return Ok(0);
    }
    Ok(0)
}

fn builtin_eval(args: &[String], executor: &mut Executor) -> Result<i32, ShellError> {
    if args.is_empty() {
        return Ok(0);
    }
    let input = args.join(" ");
    match crate::parser::Parser::new_with_aliases(&input, &executor.env.aliases).parse_program() {
        Ok(program) => Ok(executor.exec_program(&program)),
        Err(e) => {
            eprintln!("yosh: eval: {}", e);
            Ok(2)
        }
    }
}

fn builtin_exec(args: &[String], env: &mut ShellEnv) -> Result<i32, ShellError> {
    if args.is_empty() {
        return Ok(0);
    }
    let cmd = &args[0];

    // Resolve the executable path. If the command contains `/`, treat as
    // a relative or absolute path. Otherwise walk $PATH.
    let resolved_path: std::path::PathBuf = if cmd.contains('/') {
        std::path::PathBuf::from(cmd)
    } else {
        let path_var = env
            .vars
            .get("PATH")
            .map(|s| s.to_string())
            .unwrap_or_default();
        match crate::exec::command::find_in_path(cmd, &path_var, &mut env.utility_hash) {
            Some(p) => p,
            None => {
                return Err(ShellError::runtime(
                    RuntimeErrorKind::CommandNotFound,
                    format!("exec: {}: not found", cmd),
                ));
            }
        }
    };

    let c_path = match CString::new(resolved_path.as_os_str().as_encoded_bytes()) {
        Ok(s) => s,
        Err(_) => {
            return Err(ShellError::runtime(
                RuntimeErrorKind::ExecFailed,
                format!("exec: {}: invalid path", cmd),
            ));
        }
    };

    let mut c_args: Vec<CString> = Vec::with_capacity(args.len());
    for a in args {
        match CString::new(a.as_str()) {
            Ok(s) => c_args.push(s),
            Err(_) => {
                return Err(ShellError::runtime(
                    RuntimeErrorKind::ExecFailed,
                    format!("exec: {}: invalid argument", a),
                ));
            }
        }
    }

    // Build envp from currently-exported variables.
    let envp: Vec<CString> = env
        .vars
        .environ()
        .iter()
        .filter_map(|(k, v)| CString::new(format!("{}={}", k, v)).ok())
        .collect();

    let err = nix::unistd::execve(&c_path, &c_args, &envp).unwrap_err();
    use nix::errno::Errno;
    match err {
        Errno::ENOENT => Err(ShellError::runtime(
            RuntimeErrorKind::CommandNotFound,
            format!("exec: {}: not found", cmd),
        )),
        Errno::EACCES => Err(ShellError::runtime(
            RuntimeErrorKind::PermissionDenied,
            format!("exec: {}: permission denied", cmd),
        )),
        _ => Err(ShellError::runtime(
            RuntimeErrorKind::ExecFailed,
            format!("exec: {}: {}", cmd, err),
        )),
    }
}

fn builtin_trap(args: &[String], env: &mut ShellEnv) -> Result<i32, ShellError> {
    if args.is_empty() {
        env.traps.display_all();
        return Ok(0);
    }
    if args[0] == "-p" {
        env.traps.display_all();
        return Ok(0);
    }
    if args.len() == 1 {
        env.traps.remove_trap(&args[0]);
        return Ok(0);
    }
    let action_str = &args[0];
    let signals = &args[1..];
    let action = if action_str == "-" {
        TrapAction::Default
    } else if action_str.is_empty() {
        TrapAction::Ignore
    } else {
        TrapAction::Command(action_str.to_string())
    };
    let mut status = 0;
    for sig in signals {
        if matches!(action, TrapAction::Default) {
            env.traps.remove_trap(sig);
        } else if let Err(e) = env.traps.set_trap(sig, action.clone()) {
            eprintln!("yosh: {}", e);
            status = 1;
        }
    }
    Ok(status)
}

fn builtin_source(args: &[String], executor: &mut Executor) -> Result<i32, ShellError> {
    if args.is_empty() {
        return Err(ShellError::runtime(
            RuntimeErrorKind::InvalidArgument,
            ".: filename argument required".to_string(),
        ));
    }
    let filename = &args[0];
    let path = if filename.contains('/') {
        std::path::PathBuf::from(filename)
    } else {
        if let Some(path_var) = executor.env.vars.get("PATH") {
            let mut found = None;
            for dir in path_var.split(':') {
                let candidate = std::path::PathBuf::from(dir).join(filename);
                if candidate.is_file() {
                    found = Some(candidate);
                    break;
                }
            }
            match found {
                Some(p) => p,
                None => {
                    return Err(ShellError::runtime(
                        RuntimeErrorKind::IoError,
                        format!(".: {}: not found", filename),
                    ));
                }
            }
        } else {
            std::path::PathBuf::from(filename)
        }
    };
    match executor.source_file(&path) {
        Some(status) => Ok(status),
        None => Err(ShellError::runtime(
            RuntimeErrorKind::IoError,
            format!(".: {}: No such file or directory", path.display()),
        )),
    }
}

fn builtin_shift(args: &[String], env: &mut ShellEnv) -> Result<i32, ShellError> {
    let n = if args.is_empty() {
        1usize
    } else {
        match args[0].parse::<usize>() {
            Ok(n) => n,
            Err(_) => {
                return Err(ShellError::runtime(
                    RuntimeErrorKind::InvalidArgument,
                    format!("shift: {}: numeric argument required", args[0]),
                ));
            }
        }
    };
    if n > env.vars.positional_params().len() {
        return Err(ShellError::runtime(
            RuntimeErrorKind::IoError,
            "shift: shift count out of range".to_string(),
        ));
    }
    env.vars
        .set_positional_params(env.vars.positional_params()[n..].to_vec());
    Ok(0)
}

fn builtin_times(args: &[String]) -> Result<i32, ShellError> {
    if !args.is_empty() {
        return Err(ShellError::runtime(
            RuntimeErrorKind::InvalidArgument,
            format!("times: unexpected operand: {}", args[0]),
        ));
    }
    let mut tms: libc::tms = unsafe { std::mem::zeroed() };
    let ticks = unsafe { libc::sysconf(libc::_SC_CLK_TCK) } as f64;
    if unsafe { libc::times(&mut tms) } == u64::MAX {
        return Err(ShellError::runtime(
            RuntimeErrorKind::IoError,
            "times: failed".to_string(),
        ));
    }
    let fmt = |t: libc::clock_t| -> String {
        let secs = t as f64 / ticks;
        let m = (secs / 60.0) as u64;
        let s = secs - (m as f64 * 60.0);
        format!("{}m{:.3}s", m, s)
    };
    println!("{} {}", fmt(tms.tms_utime), fmt(tms.tms_stime));
    println!("{} {}", fmt(tms.tms_cutime), fmt(tms.tms_cstime));
    Ok(0)
}

// ---------------------------------------------------------------------------
// fc built-in
// ---------------------------------------------------------------------------

fn builtin_fc(args: &[String], executor: &mut Executor) -> Result<i32, ShellError> {
    if executor.env.history.entries().is_empty() {
        return Err(ShellError::runtime(
            RuntimeErrorKind::IoError,
            "fc: history is empty".to_string(),
        ));
    }

    let mut list_mode = false;
    let mut suppress_numbers = false;
    let mut reverse = false;
    let mut substitute_mode = false;
    let mut editor: Option<String> = None;
    let mut operands: Vec<String> = Vec::new();

    let mut i = 0;
    while i < args.len() {
        let arg = &args[i];
        if arg == "-e" {
            i += 1;
            if i >= args.len() {
                return Err(ShellError::runtime(
                    RuntimeErrorKind::IoError,
                    "fc: -e: option requires an argument".to_string(),
                ));
            }
            editor = Some(args[i].clone());
        } else if arg.starts_with('-')
            && arg.len() > 1
            && arg.chars().nth(1).is_some_and(|c| c.is_ascii_alphabetic())
        {
            for ch in arg[1..].chars() {
                match ch {
                    'l' => list_mode = true,
                    'n' => suppress_numbers = true,
                    'r' => reverse = true,
                    's' => substitute_mode = true,
                    _ => {
                        return Err(ShellError::runtime(
                            RuntimeErrorKind::InvalidArgument,
                            format!("fc: -{}: invalid option", ch),
                        ));
                    }
                }
            }
        } else {
            operands.push(arg.clone());
        }
        i += 1;
    }

    if substitute_mode {
        return fc_substitute(&operands, executor);
    }

    // Clone history entries to release the immutable borrow on executor,
    // allowing fc_edit to take &mut Executor.
    let entries: Vec<String> = executor.env.history.entries().to_vec();
    let hist_len = entries.len();
    let (start, end) = fc_resolve_range(&operands, hist_len, list_mode, &entries);

    if list_mode {
        fc_list(&entries, start, end, suppress_numbers, reverse);
        Ok(0)
    } else {
        fc_edit(&entries, start, end, reverse, editor, executor)
    }
}

fn fc_resolve_one(spec: &str, default: usize, entries: &[String]) -> usize {
    if let Ok(n) = spec.parse::<i64>() {
        if n > 0 {
            ((n - 1) as usize).min(entries.len().saturating_sub(1))
        } else {
            entries.len().saturating_sub((-n) as usize)
        }
    } else {
        (0..entries.len())
            .rev()
            .find(|&i| entries[i].starts_with(spec))
            .unwrap_or(default)
    }
}

fn fc_resolve_range(
    operands: &[String],
    hist_len: usize,
    is_list: bool,
    entries: &[String],
) -> (usize, usize) {
    match operands.len() {
        0 => {
            if is_list {
                (hist_len.saturating_sub(16), hist_len.saturating_sub(1))
            } else {
                let last = hist_len.saturating_sub(1);
                (last, last)
            }
        }
        1 => {
            let idx = fc_resolve_one(&operands[0], hist_len.saturating_sub(1), entries);
            if is_list {
                (idx, hist_len.saturating_sub(1))
            } else {
                (idx, idx)
            }
        }
        _ => {
            let s = fc_resolve_one(&operands[0], hist_len.saturating_sub(1), entries);
            let e = fc_resolve_one(&operands[1], hist_len.saturating_sub(1), entries);
            (s, e)
        }
    }
}

fn fc_list(entries: &[String], start: usize, end: usize, suppress_numbers: bool, reverse: bool) {
    let (lo, hi) = if start <= end {
        (start, end)
    } else {
        (end, start)
    };
    let range: Vec<usize> = if reverse ^ (start > end) {
        (lo..=hi).rev().collect()
    } else {
        (lo..=hi).collect()
    };
    for i in range {
        if suppress_numbers {
            println!("\t{}", entries[i]);
        } else {
            println!("{}\t{}", i + 1, entries[i]);
        }
    }
}

fn fc_edit(
    entries: &[String],
    start: usize,
    end: usize,
    reverse: bool,
    editor: Option<String>,
    executor: &mut Executor,
) -> Result<i32, ShellError> {
    let editor_cmd = editor
        .or_else(|| executor.env.vars.get("FCEDIT").map(|s| s.to_string()))
        .or_else(|| executor.env.vars.get("EDITOR").map(|s| s.to_string()))
        .unwrap_or_else(|| "/bin/ed".to_string());

    let (lo, hi) = if start <= end {
        (start, end)
    } else {
        (end, start)
    };
    let mut commands: Vec<&str> = (lo..=hi).map(|i| entries[i].as_str()).collect();
    if reverse {
        commands.reverse();
    }

    let tmp_path = match create_secure_tempfile("yosh_fc") {
        Ok(path) => path,
        Err(e) => {
            return Err(ShellError::runtime(
                RuntimeErrorKind::IoError,
                format!("fc: {}", e),
            ));
        }
    };
    {
        use std::fs::OpenOptions;
        use std::os::unix::fs::OpenOptionsExt;
        let mut file = match OpenOptions::new().write(true).mode(0o600).open(&tmp_path) {
            Ok(f) => f,
            Err(e) => {
                let _ = std::fs::remove_file(&tmp_path);
                return Err(ShellError::runtime(
                    RuntimeErrorKind::IoError,
                    format!("fc: cannot open temp file: {}", e),
                ));
            }
        };
        for cmd in &commands {
            let _ = writeln!(file, "{}", cmd);
        }
    }

    use std::process::Command;
    let status = Command::new(&editor_cmd).arg(&tmp_path).status();
    match status {
        Ok(s) if s.success() => {}
        Ok(s) => {
            let _ = std::fs::remove_file(&tmp_path);
            return Ok(s.code().unwrap_or(1));
        }
        Err(e) => {
            let _ = std::fs::remove_file(&tmp_path);
            return Err(ShellError::runtime(
                RuntimeErrorKind::CommandNotFound,
                format!("fc: {}: {}", editor_cmd, e),
            ));
        }
    }

    let content = match std::fs::read_to_string(&tmp_path) {
        Ok(c) => c,
        Err(e) => {
            let _ = std::fs::remove_file(&tmp_path);
            return Err(ShellError::runtime(
                RuntimeErrorKind::IoError,
                format!("fc: cannot read temp file: {}", e),
            ));
        }
    };
    let _ = std::fs::remove_file(&tmp_path);

    if content.trim().is_empty() {
        return Ok(0);
    }

    executor.eval_string(&content);
    Ok(executor.env.exec.last_exit_status)
}

fn fc_substitute(operands: &[String], executor: &mut Executor) -> Result<i32, ShellError> {
    let entries = executor.env.history.entries();
    if entries.is_empty() {
        return Err(ShellError::runtime(
            RuntimeErrorKind::IoError,
            "fc: history is empty".to_string(),
        ));
    }

    let mut replacement: Option<(&str, &str)> = None;
    let mut target_spec: Option<&str> = None;

    for op in operands {
        if let Some(eq_pos) = op.find('=') {
            replacement = Some((&op[..eq_pos], &op[eq_pos + 1..]));
        } else {
            target_spec = Some(op.as_str());
        }
    }

    let idx = if let Some(spec) = target_spec {
        fc_resolve_one(spec, entries.len().saturating_sub(1), entries)
    } else {
        entries.len().saturating_sub(1)
    };

    let mut cmd = entries[idx].clone();
    if let Some((old, new)) = replacement {
        cmd = cmd.replacen(old, new, 1);
    }

    // Informational output — not an error
    eprintln!("{}", cmd);

    let histsize: usize = executor
        .env
        .vars
        .get("HISTSIZE")
        .and_then(|s| s.parse().ok())
        .unwrap_or(500);
    let histcontrol = executor
        .env
        .vars
        .get("HISTCONTROL")
        .unwrap_or("ignoreboth")
        .to_string();
    executor.env.history.add(&cmd, histsize, &histcontrol);

    executor.eval_string(&cmd);
    Ok(executor.env.exec.last_exit_status)
}

/// Create a temporary file with a random name and restrictive permissions (0o600).
/// Uses `O_CREAT | O_EXCL` to atomically create the file, preventing TOCTOU races.
fn create_secure_tempfile(prefix: &str) -> Result<String, String> {
    use std::collections::hash_map::RandomState;
    use std::fs::OpenOptions;
    use std::hash::{BuildHasher, Hasher};
    use std::os::unix::fs::OpenOptionsExt;

    let tmp_dir = std::env::var("TMPDIR").unwrap_or_else(|_| "/tmp".to_string());

    for _ in 0..16 {
        let s = RandomState::new();
        let mut hasher = s.build_hasher();
        hasher.write_u64(std::process::id() as u64);
        let rand_hex = format!("{:016x}", hasher.finish());
        let path = format!("{}/{}_{}", tmp_dir, prefix, rand_hex);

        match OpenOptions::new()
            .write(true)
            .create_new(true)
            .mode(0o600)
            .open(&path)
        {
            Ok(_) => return Ok(path),
            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
            Err(e) => return Err(format!("cannot create temp file: {}", e)),
        }
    }

    Err("cannot create temp file: too many collisions".to_string())
}

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

    #[test]
    fn exit_builtin_sets_exit_requested_in_interactive_mode() {
        let mut executor = Executor::new("yosh", vec![]);
        executor.env.mode.is_interactive = true;
        let status = exec_special_builtin("exit", &["42".to_string()], &mut executor);
        assert_eq!(status, 42);
        assert_eq!(executor.exit_requested, Some(42));
    }

    #[test]
    fn exit_builtin_uses_last_status_when_no_args() {
        let mut executor = Executor::new("yosh", vec![]);
        executor.env.mode.is_interactive = true;
        executor.env.exec.last_exit_status = 7;
        exec_special_builtin("exit", &[], &mut executor);
        assert_eq!(executor.exit_requested, Some(7));
    }

    #[test]
    fn unset_rejects_invalid_identifier() {
        let mut executor = Executor::new("yosh", vec![]);
        let status = exec_special_builtin("unset", &["1foo".to_string()], &mut executor);
        assert_eq!(status, 1);
    }

    #[test]
    fn readonly_rejects_invalid_identifier() {
        let mut executor = Executor::new("yosh", vec![]);
        let status = exec_special_builtin("readonly", &["1foo=v".to_string()], &mut executor);
        assert_eq!(status, 1);
    }

    #[test]
    fn export_rejects_invalid_identifier() {
        let mut executor = Executor::new("yosh", vec![]);
        let status = exec_special_builtin("export", &["1foo=v".to_string()], &mut executor);
        assert_eq!(status, 1);
    }

    #[test]
    fn unset_f_removes_function() {
        let mut executor = Executor::new("yosh", vec![]);
        executor.eval_string("foo() { :; }");
        assert!(executor.env.functions.contains_key("foo"));
        let status = exec_special_builtin(
            "unset",
            &["-f".to_string(), "foo".to_string()],
            &mut executor,
        );
        assert_eq!(status, 0);
        assert!(!executor.env.functions.contains_key("foo"));
    }

    #[test]
    fn unset_f_keeps_variable_of_same_name() {
        let mut executor = Executor::new("yosh", vec![]);
        executor.eval_string("foo() { :; }");
        executor.env.vars.set("foo", "bar").unwrap();
        exec_special_builtin(
            "unset",
            &["-f".to_string(), "foo".to_string()],
            &mut executor,
        );
        assert_eq!(executor.env.vars.get("foo"), Some("bar"));
        assert!(!executor.env.functions.contains_key("foo"));
    }

    #[test]
    fn unset_rejects_combined_f_v() {
        let mut executor = Executor::new("yosh", vec![]);
        let status = exec_special_builtin(
            "unset",
            &["-f".to_string(), "-v".to_string(), "x".to_string()],
            &mut executor,
        );
        assert_eq!(status, 2);
    }

    #[test]
    fn unset_rejects_clustered_fv_flag() {
        let mut executor = Executor::new("yosh", vec![]);
        let status = exec_special_builtin(
            "unset",
            &["-fv".to_string(), "x".to_string()],
            &mut executor,
        );
        assert_eq!(status, 2);
    }

    #[test]
    fn readonly_p_lists_readonly_var() {
        let mut executor = Executor::new("yosh", vec![]);
        exec_special_builtin("readonly", &["myvar=v".to_string()], &mut executor);
        let status = exec_special_builtin("readonly", &["-p".to_string()], &mut executor);
        assert_eq!(status, 0);
        // The actual listing is on stdout (println!) which we don't capture here;
        // smoke-test via the e2e suite for output content.
    }

    #[test]
    fn break_outside_loop_returns_one_and_no_flow_control() {
        let mut executor = Executor::new("yosh", vec![]);
        let status = exec_special_builtin("break", &[], &mut executor);
        assert_eq!(status, 1);
        assert!(executor.env.exec.flow_control.is_none());
    }

    #[test]
    fn continue_outside_loop_returns_one_and_no_flow_control() {
        let mut executor = Executor::new("yosh", vec![]);
        let status = exec_special_builtin("continue", &[], &mut executor);
        assert_eq!(status, 1);
        assert!(executor.env.exec.flow_control.is_none());
    }

    #[test]
    fn continue_n_is_clamped_to_loop_depth() {
        use crate::env::FlowControl;
        let mut executor = Executor::new("yosh", vec![]);
        executor.env.exec.loop_depth = 1;
        let status = exec_special_builtin("continue", &["5".to_string()], &mut executor);
        assert_eq!(status, 0);
        assert_eq!(
            executor.env.exec.flow_control,
            Some(FlowControl::Continue(1))
        );
    }

    #[test]
    fn break_n_is_clamped_to_loop_depth() {
        use crate::env::FlowControl;
        let mut executor = Executor::new("yosh", vec![]);
        executor.env.exec.loop_depth = 2;
        let status = exec_special_builtin("break", &["7".to_string()], &mut executor);
        assert_eq!(status, 0);
        assert_eq!(executor.env.exec.flow_control, Some(FlowControl::Break(2)));
    }
}