kaish-kernel 0.8.1

Core kernel for kaish: lexer, parser, interpreter, and runtime
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
//! Variable scope management for kaish.
//!
//! Scopes provide variable bindings with:
//! - Nested scope frames (push/pop for loops, tool calls)
//! - The special `$?` variable holding the last command's exit code
//! - Path resolution for nested access (`${VAR.field[0]}`)

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

use crate::ast::{Value, VarPath, VarSegment};

use super::result::ExecResult;

/// Variable scope with nested frames and last-result tracking.
///
/// Variables are looked up from innermost to outermost frame.
/// The `?` variable always refers to the last command result.
///
/// The `frames` field is wrapped in `Arc` for copy-on-write (COW) semantics.
/// Cloning a Scope is O(1) — just bumps the Arc refcount. Mutations use
/// `Arc::make_mut` to clone the inner data only when shared. This matters
/// because `execute_pipeline` snapshots the scope into ExecContext (clone)
/// and syncs it back (clone) on every command.
#[derive(Debug, Clone)]
pub struct Scope {
    /// Stack of variable frames. Last element is the innermost scope.
    /// Wrapped in Arc for copy-on-write: clone is O(1), mutation clones on demand.
    frames: Arc<Vec<HashMap<String, Value>>>,
    /// Variables marked for export to child processes.
    exported: HashSet<String>,
    /// The result of the last command execution.
    last_result: ExecResult,
    /// Script or tool name ($0).
    script_name: String,
    /// Positional arguments ($1-$9, $@, $#).
    positional: Vec<String>,
    /// Error exit mode (set -e): exit on any command failure.
    error_exit: bool,
    /// Counter for temporarily suppressing errexit (e.g. inside && / || left side).
    /// When > 0, error_exit_enabled() returns false even if error_exit is true.
    errexit_suppressed: usize,
    /// AST display mode (kaish-ast -on/-off): show AST instead of executing.
    show_ast: bool,
    /// Latch mode (set -o latch): gate dangerous operations behind nonce confirmation.
    latch_enabled: bool,
    /// Trash mode (set -o trash): move deleted files to freedesktop.org Trash.
    trash_enabled: bool,
    /// Maximum file size (bytes) for trash. Files larger than this bypass trash.
    /// Default: 10 MB.
    trash_max_size: u64,
    /// Glob expansion mode (set -o glob): expand bare glob patterns in arguments.
    glob_enabled: bool,
    /// Kaish session identifier ($$). A monotonic counter assigned at Kernel
    /// construction (see `KERNEL_COUNTER` in kernel.rs) — *not* the OS PID.
    /// Subshells / forks inherit the parent's value (Scope clone copies it).
    /// 0 is a sentinel meaning "this scope was constructed outside a Kernel"
    /// (e.g. arithmetic unit tests, kaish-clear before its setter runs).
    pid: u64,
}

impl Scope {
    /// Create a new scope with one empty frame.
    ///
    /// `pid` defaults to 0 (sentinel). The owning Kernel calls `set_pid()`
    /// during construction to assign the real session identifier.
    pub fn new() -> Self {
        Self {
            frames: Arc::new(vec![HashMap::new()]),
            exported: HashSet::new(),
            last_result: ExecResult::default(),
            script_name: String::new(),
            positional: Vec::new(),
            error_exit: false,
            errexit_suppressed: 0,
            show_ast: false,
            latch_enabled: false,
            trash_enabled: false,
            trash_max_size: 10 * 1024 * 1024, // 10 MB
            glob_enabled: true,
            pid: 0,
        }
    }

    /// Get the kaish session identifier ($$).
    pub fn pid(&self) -> u64 {
        self.pid
    }

    /// Set the kaish session identifier ($$). Called by the Kernel during
    /// construction to thread the assigned counter value into the scope.
    /// Also used by `kaish-clear` to preserve $$ across a session reset.
    pub fn set_pid(&mut self, pid: u64) {
        self.pid = pid;
    }

    /// Push a new scope frame (for entering a loop, tool call, etc.)
    pub fn push_frame(&mut self) {
        Arc::make_mut(&mut self.frames).push(HashMap::new());
    }

    /// Pop the innermost scope frame.
    ///
    /// Panics if attempting to pop the last frame.
    pub fn pop_frame(&mut self) {
        if self.frames.len() > 1 {
            Arc::make_mut(&mut self.frames).pop();
        } else {
            panic!("cannot pop the root scope frame");
        }
    }

    /// Set a variable in the current (innermost) frame.
    ///
    /// Use this for `local` variable declarations.
    pub fn set(&mut self, name: impl Into<String>, value: Value) {
        if let Some(frame) = Arc::make_mut(&mut self.frames).last_mut() {
            frame.insert(name.into(), value);
        }
    }

    /// Set a variable with global semantics (shell default).
    ///
    /// If the variable exists in any frame, update it there.
    /// Otherwise, create it in the outermost (root) frame.
    /// Use this for non-local variable assignments.
    pub fn set_global(&mut self, name: impl Into<String>, value: Value) {
        let name = name.into();

        // Search from innermost to outermost to find existing variable
        let frames = Arc::make_mut(&mut self.frames);
        for frame in frames.iter_mut().rev() {
            if let std::collections::hash_map::Entry::Occupied(mut e) = frame.entry(name.clone()) {
                e.insert(value);
                return;
            }
        }

        // Variable doesn't exist - create in root frame (index 0)
        if let Some(frame) = frames.first_mut() {
            frame.insert(name, value);
        }
    }

    /// Get a variable by name, searching from innermost to outermost frame.
    pub fn get(&self, name: &str) -> Option<&Value> {
        for frame in self.frames.iter().rev() {
            if let Some(value) = frame.get(name) {
                return Some(value);
            }
        }
        None
    }

    /// Remove a variable, searching from innermost to outermost frame.
    ///
    /// Returns the removed value if found, None otherwise.
    pub fn remove(&mut self, name: &str) -> Option<Value> {
        for frame in Arc::make_mut(&mut self.frames).iter_mut().rev() {
            if let Some(value) = frame.remove(name) {
                return Some(value);
            }
        }
        None
    }

    /// Set the last command result (accessible via `$?`).
    pub fn set_last_result(&mut self, result: ExecResult) {
        self.last_result = result;
    }

    /// Get the last command result.
    pub fn last_result(&self) -> &ExecResult {
        &self.last_result
    }

    /// Set the positional parameters ($0, $1-$9, $@, $#).
    ///
    /// The script_name becomes $0, and args become $1, $2, etc.
    pub fn set_positional(&mut self, script_name: impl Into<String>, args: Vec<String>) {
        self.script_name = script_name.into();
        self.positional = args;
    }

    /// Save current positional parameters for later restoration.
    ///
    /// Returns (script_name, args) tuple that can be passed to set_positional.
    pub fn save_positional(&self) -> (String, Vec<String>) {
        (self.script_name.clone(), self.positional.clone())
    }

    /// Get a positional parameter by index ($0-$9).
    ///
    /// $0 returns the script name, $1-$9 return arguments.
    pub fn get_positional(&self, n: usize) -> Option<&str> {
        if n == 0 {
            if self.script_name.is_empty() {
                None
            } else {
                Some(&self.script_name)
            }
        } else {
            self.positional.get(n - 1).map(|s| s.as_str())
        }
    }

    /// Get all positional arguments as a slice ($@).
    pub fn all_args(&self) -> &[String] {
        &self.positional
    }

    /// Get the count of positional arguments ($#).
    pub fn arg_count(&self) -> usize {
        self.positional.len()
    }

    /// Check if error-exit mode is active (set -e and not suppressed).
    ///
    /// Returns false when inside the left side of `&&` or `||` chains,
    /// matching bash behavior where those operators handle failure themselves.
    pub fn error_exit_enabled(&self) -> bool {
        self.error_exit && self.errexit_suppressed == 0
    }

    /// Set error-exit mode (set -e / set +e).
    pub fn set_error_exit(&mut self, enabled: bool) {
        self.error_exit = enabled;
    }

    /// Suppress errexit temporarily (for `&&`/`||` left side).
    pub fn suppress_errexit(&mut self) {
        self.errexit_suppressed += 1;
    }

    /// Unsuppress errexit (after `&&`/`||` left side completes).
    pub fn unsuppress_errexit(&mut self) {
        self.errexit_suppressed = self.errexit_suppressed.saturating_sub(1);
    }

    /// Check if AST display mode is enabled (kaish-ast -on).
    pub fn show_ast(&self) -> bool {
        self.show_ast
    }

    /// Set AST display mode (kaish-ast -on / kaish-ast -off).
    pub fn set_show_ast(&mut self, enabled: bool) {
        self.show_ast = enabled;
    }

    /// Check if latch mode is enabled (set -o latch).
    pub fn latch_enabled(&self) -> bool {
        self.latch_enabled
    }

    /// Set latch mode (set -o latch / set +o latch).
    pub fn set_latch_enabled(&mut self, enabled: bool) {
        self.latch_enabled = enabled;
    }

    /// Check if trash mode is enabled (set -o trash).
    pub fn trash_enabled(&self) -> bool {
        self.trash_enabled
    }

    /// Set trash mode (set -o trash / set +o trash).
    pub fn set_trash_enabled(&mut self, enabled: bool) {
        self.trash_enabled = enabled;
    }

    /// Get the maximum file size for trash (bytes).
    pub fn trash_max_size(&self) -> u64 {
        self.trash_max_size
    }

    /// Set the maximum file size for trash (bytes).
    pub fn set_trash_max_size(&mut self, size: u64) {
        self.trash_max_size = size;
    }

    /// Check if glob expansion is enabled (set -o glob, default true).
    pub fn glob_enabled(&self) -> bool {
        self.glob_enabled
    }

    /// Set glob expansion mode (set -o glob / set +o glob).
    pub fn set_glob_enabled(&mut self, enabled: bool) {
        self.glob_enabled = enabled;
    }

    /// Mark a variable as exported (visible to child processes).
    ///
    /// The variable doesn't need to exist yet; it will be exported when set.
    pub fn export(&mut self, name: impl Into<String>) {
        self.exported.insert(name.into());
    }

    /// Check if a variable is marked for export.
    pub fn is_exported(&self, name: &str) -> bool {
        self.exported.contains(name)
    }

    /// Set a variable and mark it as exported.
    pub fn set_exported(&mut self, name: impl Into<String>, value: Value) {
        let name = name.into();
        self.set(&name, value);
        self.export(name);
    }

    /// Unmark a variable from export.
    pub fn unexport(&mut self, name: &str) {
        self.exported.remove(name);
    }

    /// Get all exported variables with their values.
    ///
    /// Only returns variables that exist and are marked for export.
    pub fn exported_vars(&self) -> Vec<(String, Value)> {
        let mut result = Vec::new();
        for name in &self.exported {
            if let Some(value) = self.get(name) {
                result.push((name.clone(), value.clone()));
            }
        }
        result.sort_by(|(a, _), (b, _)| a.cmp(b));
        result
    }

    /// Get all exported variable names.
    pub fn exported_names(&self) -> Vec<&str> {
        let mut names: Vec<&str> = self.exported.iter().map(|s| s.as_str()).collect();
        names.sort();
        names
    }

    /// Resolve a variable path like `${VAR}` or `${VAR.field}`.
    ///
    /// Returns None if the path cannot be resolved.
    /// `$?` resolves to the previous command's exit code as an int;
    /// field access on `$?` is rejected by the validator before reaching here.
    pub fn resolve_path(&self, path: &VarPath) -> Option<Value> {
        if path.segments.is_empty() {
            return None;
        }

        // Get the root variable name
        let VarSegment::Field(root_name) = &path.segments[0];

        // Special case: $? (last result)
        if root_name == "?" {
            return self.resolve_result_path(&path.segments[1..]);
        }

        // For regular variables, only simple access is supported
        if path.segments.len() > 1 {
            return None; // No nested field access for regular variables
        }

        self.get(root_name).cloned()
    }

    /// Resolve path segments on the last result ($?).
    ///
    /// `$?` alone returns the exit code as an integer (POSIX-shaped).
    /// Field access on `$?` was removed — the validator rejects it with
    /// a pointer to `kaish-last`, which exposes the previous command's
    /// structured data (or stdout) as text.
    fn resolve_result_path(&self, segments: &[VarSegment]) -> Option<Value> {
        if segments.is_empty() {
            return Some(Value::Int(self.last_result.code));
        }
        None
    }

    /// Check if a variable exists in any frame.
    pub fn contains(&self, name: &str) -> bool {
        self.get(name).is_some()
    }

    /// Get all variable names in scope (for debugging/introspection).
    pub fn all_names(&self) -> Vec<&str> {
        let mut names: Vec<&str> = self
            .frames
            .iter()
            .flat_map(|f| f.keys().map(|s| s.as_str()))
            .collect();
        names.sort();
        names.dedup();
        names
    }

    /// Get all variables as (name, value) pairs.
    ///
    /// Variables are deduplicated, with inner frames shadowing outer ones.
    pub fn all(&self) -> Vec<(String, Value)> {
        let mut result = std::collections::HashMap::new();
        // Iterate outer to inner so inner frames override
        for frame in self.frames.iter() {
            for (name, value) in frame {
                result.insert(name.clone(), value.clone());
            }
        }
        let mut pairs: Vec<_> = result.into_iter().collect();
        pairs.sort_by(|(a, _), (b, _)| a.cmp(b));
        pairs
    }
}

impl Default for Scope {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn new_scope_has_one_frame() {
        let scope = Scope::new();
        assert_eq!(scope.frames.len(), 1);
    }

    #[test]
    fn set_and_get_variable() {
        let mut scope = Scope::new();
        scope.set("X", Value::Int(42));
        assert_eq!(scope.get("X"), Some(&Value::Int(42)));
    }

    #[test]
    fn get_nonexistent_returns_none() {
        let scope = Scope::new();
        assert_eq!(scope.get("MISSING"), None);
    }

    #[test]
    fn inner_frame_shadows_outer() {
        let mut scope = Scope::new();
        scope.set("X", Value::Int(1));
        scope.push_frame();
        scope.set("X", Value::Int(2));
        assert_eq!(scope.get("X"), Some(&Value::Int(2)));
        scope.pop_frame();
        assert_eq!(scope.get("X"), Some(&Value::Int(1)));
    }

    #[test]
    fn inner_frame_can_see_outer_vars() {
        let mut scope = Scope::new();
        scope.set("OUTER", Value::String("visible".into()));
        scope.push_frame();
        assert_eq!(scope.get("OUTER"), Some(&Value::String("visible".into())));
    }

    #[test]
    fn resolve_simple_path() {
        let mut scope = Scope::new();
        scope.set("NAME", Value::String("Alice".into()));

        let path = VarPath::simple("NAME");
        assert_eq!(
            scope.resolve_path(&path),
            Some(Value::String("Alice".into()))
        );
    }

    #[test]
    fn resolve_bare_last_result_returns_exit_code() {
        let mut scope = Scope::new();
        scope.set_last_result(ExecResult::failure(127, "not found"));

        let path = VarPath {
            segments: vec![VarSegment::Field("?".into())],
        };
        assert_eq!(scope.resolve_path(&path), Some(Value::Int(127)));
    }

    #[test]
    fn resolve_last_result_field_access_is_rejected() {
        // Field access on $? was removed — use `kaish-last` for structured data.
        // The resolver returns None; the validator catches it earlier with a
        // specific error code so users see actionable diagnostics.
        let mut scope = Scope::new();
        scope.set_last_result(ExecResult::success_with_data(
            "1",
            Value::Json(serde_json::json!({"count": 5})),
        ));

        let path = VarPath {
            segments: vec![
                VarSegment::Field("?".into()),
                VarSegment::Field("data".into()),
            ],
        };
        assert_eq!(scope.resolve_path(&path), None);
    }

    #[test]
    fn resolve_invalid_path_returns_none() {
        let mut scope = Scope::new();
        scope.set("X", Value::Int(42));

        // Cannot do field access on an int
        let path = VarPath {
            segments: vec![
                VarSegment::Field("X".into()),
                VarSegment::Field("invalid".into()),
            ],
        };
        assert_eq!(scope.resolve_path(&path), None);
    }

    #[test]
    fn contains_finds_variable() {
        let mut scope = Scope::new();
        scope.set("EXISTS", Value::Bool(true));
        assert!(scope.contains("EXISTS"));
        assert!(!scope.contains("MISSING"));
    }

    #[test]
    fn all_names_lists_variables() {
        let mut scope = Scope::new();
        scope.set("A", Value::Int(1));
        scope.set("B", Value::Int(2));
        scope.push_frame();
        scope.set("C", Value::Int(3));

        let names = scope.all_names();
        assert!(names.contains(&"A"));
        assert!(names.contains(&"B"));
        assert!(names.contains(&"C"));
    }

    #[test]
    #[should_panic(expected = "cannot pop the root scope frame")]
    fn pop_root_frame_panics() {
        let mut scope = Scope::new();
        scope.pop_frame();
    }

    #[test]
    fn positional_params_basic() {
        let mut scope = Scope::new();
        scope.set_positional("my_tool", vec!["arg1".into(), "arg2".into(), "arg3".into()]);

        // $0 is the script/tool name
        assert_eq!(scope.get_positional(0), Some("my_tool"));
        // $1, $2, $3 are the arguments
        assert_eq!(scope.get_positional(1), Some("arg1"));
        assert_eq!(scope.get_positional(2), Some("arg2"));
        assert_eq!(scope.get_positional(3), Some("arg3"));
        // $4 doesn't exist
        assert_eq!(scope.get_positional(4), None);
    }

    #[test]
    fn positional_params_empty() {
        let scope = Scope::new();
        // No positional params set
        assert_eq!(scope.get_positional(0), None);
        assert_eq!(scope.get_positional(1), None);
        assert_eq!(scope.arg_count(), 0);
        assert!(scope.all_args().is_empty());
    }

    #[test]
    fn all_args_returns_slice() {
        let mut scope = Scope::new();
        scope.set_positional("test", vec!["a".into(), "b".into(), "c".into()]);

        let args = scope.all_args();
        assert_eq!(args, &["a", "b", "c"]);
    }

    #[test]
    fn arg_count_returns_count() {
        let mut scope = Scope::new();
        scope.set_positional("test", vec!["one".into(), "two".into()]);

        assert_eq!(scope.arg_count(), 2);
    }

    #[test]
    fn export_marks_variable() {
        let mut scope = Scope::new();
        scope.set("X", Value::Int(42));

        assert!(!scope.is_exported("X"));
        scope.export("X");
        assert!(scope.is_exported("X"));
    }

    #[test]
    fn set_exported_sets_and_exports() {
        let mut scope = Scope::new();
        scope.set_exported("PATH", Value::String("/usr/bin".into()));

        assert!(scope.is_exported("PATH"));
        assert_eq!(scope.get("PATH"), Some(&Value::String("/usr/bin".into())));
    }

    #[test]
    fn unexport_removes_export_marker() {
        let mut scope = Scope::new();
        scope.set_exported("VAR", Value::Int(1));
        assert!(scope.is_exported("VAR"));

        scope.unexport("VAR");
        assert!(!scope.is_exported("VAR"));
        // Variable still exists, just not exported
        assert!(scope.get("VAR").is_some());
    }

    #[test]
    fn exported_vars_returns_only_exported_with_values() {
        let mut scope = Scope::new();
        scope.set_exported("A", Value::Int(1));
        scope.set_exported("B", Value::Int(2));
        scope.set("C", Value::Int(3)); // Not exported
        scope.export("D"); // Exported but no value

        let exported = scope.exported_vars();
        assert_eq!(exported.len(), 2);
        assert_eq!(exported[0], ("A".to_string(), Value::Int(1)));
        assert_eq!(exported[1], ("B".to_string(), Value::Int(2)));
    }

    #[test]
    fn exported_names_returns_sorted_names() {
        let mut scope = Scope::new();
        scope.export("Z");
        scope.export("A");
        scope.export("M");

        let names = scope.exported_names();
        assert_eq!(names, vec!["A", "M", "Z"]);
    }
}