Skip to main content

kaish_kernel/interpreter/
scope.rs

1//! Variable scope management for kaish.
2//!
3//! Scopes provide variable bindings with:
4//! - Nested scope frames (push/pop for loops, tool calls)
5//! - The special `$?` variable holding the last command's exit code
6//! - Path resolution for nested access (`${VAR.field[0]}`)
7
8use std::borrow::Cow;
9use std::collections::{HashMap, HashSet};
10use std::sync::Arc;
11
12use kaish_types::{json_to_value_no_envelope, value_to_json};
13
14use crate::ast::{Value, VarPath, VarSegment};
15
16use super::eval::value_to_string;
17use super::result::ExecResult;
18
19/// Why a variable path failed to resolve.
20///
21/// The three-way split is load-bearing for `${path:-default}` (decision A): the
22/// default fires on **absence** but never on a **shape** error — a wrong-typed
23/// access is a bug, not a missing value. All three are loud for a bare access;
24/// they diverge only when `:-` is present (see the default handling), where
25/// `UndefinedRoot`/`Absence` yield the default and `Shape` still shouts.
26///
27/// - `UndefinedRoot` — the root variable (or an unset dynamic `$k` subscript) is
28///   not in scope. Soft in string interpolation (expands to empty, matching
29///   bash), loud in expression position.
30/// - `Absence` — the path is well-shaped but the target isn't there: a missing
31///   record key or an out-of-bounds list index.
32/// - `Shape` — the access is wrong for the value: a string key on a list, an
33///   integer index on a record, subscripting a scalar, a dotted (non-bracket)
34///   segment, or slicing a record. Never suppressed by `:-`.
35///
36/// A loud error is surfaced everywhere, including inside strings; it is NEVER
37/// silently swallowed to an empty expansion.
38#[derive(Debug, Clone, PartialEq)]
39pub enum PathError {
40    /// The root variable is not in scope (or an unset dynamic `$k` subscript).
41    UndefinedRoot(String),
42    /// A missing key or out-of-bounds index — absence, not misuse.
43    Absence(String),
44    /// A wrong-for-the-shape access. Message ready to display.
45    Shape(String),
46}
47
48/// A human-readable type name for a value, for path error messages.
49fn type_name(value: &Value) -> &'static str {
50    match value {
51        Value::Null => "null",
52        Value::Bool(_) => "a boolean",
53        Value::Int(_) => "an integer",
54        Value::Float(_) => "a float",
55        Value::String(_) => "a string",
56        Value::Json(serde_json::Value::Array(_)) => "a list",
57        Value::Json(serde_json::Value::Object(_)) => "a record",
58        Value::Json(_) => "a scalar",
59        Value::Bytes(_) => "binary data",
60    }
61}
62
63/// A dynamic subscript value usable as a list index: an integer, or a string
64/// that parses as one (`k=1; ${xs[$k]}`).
65fn value_as_index(value: &Value) -> Option<i64> {
66    match value {
67        Value::Int(i) => Some(*i),
68        Value::String(s) => s.parse::<i64>().ok(),
69        _ => None,
70    }
71}
72
73/// A concrete, container-resolved subscript. [`resolve_step`] produces one per
74/// hop *after* seeing the container — negative indices normalized, bounds
75/// checked, dynamic keys looked up — so read traversal and (next phase) lvalue
76/// writes share one classification and can never drift. Record-key *presence*
77/// is deliberately NOT decided here: that is per-hop walk policy (a read errors
78/// on a missing key; a write leaf inserts it).
79#[derive(Debug, Clone, PartialEq)]
80enum Step {
81    /// A validated, in-bounds list index.
82    Index(usize),
83    /// A record key (existence unchecked — see the type doc).
84    Key(String),
85    /// A normalized, end-exclusive slice range (`s <= e <= len`).
86    Slice(usize, usize),
87}
88
89/// Classify a list index against an array. Negative indices count from the end;
90/// out of bounds is a loud error, and an integer subscript on a record is an
91/// error (keys are strings — the design's "integers index lists" rule). The
92/// container is a collection by [`resolve_step`]'s guard, so the scalar arm is
93/// unreachable.
94fn classify_index(json: &serde_json::Value, i: i64, path: &str) -> Result<Step, PathError> {
95    let arr = match json {
96        serde_json::Value::Array(a) => a,
97        serde_json::Value::Object(_) => {
98            return Err(PathError::Shape(format!(
99                "${{{path}[{i}]}}: integer index on a record — record keys are strings, use ${{{path}[\"{i}\"]}}"
100            )))
101        }
102        _ => unreachable!("resolve_step guards non-collection containers"),
103    };
104    let len = arr.len() as i64;
105    let idx = if i < 0 { len + i } else { i };
106    if idx < 0 || idx >= len {
107        return Err(PathError::Absence(format!(
108            "${{{path}[{i}]}}: index out of bounds (list length {len})"
109        )));
110    }
111    Ok(Step::Index(idx as usize))
112}
113
114/// Classify a record key against an object. A bareword/string key on a list is
115/// an error; key *presence* is checked when the step is applied ([`descend`]),
116/// not here — the read/write split lives in that leaf policy.
117fn classify_key(json: &serde_json::Value, key: &str, path: &str) -> Result<Step, PathError> {
118    match json {
119        serde_json::Value::Object(_) => Ok(Step::Key(key.to_string())),
120        serde_json::Value::Array(_) => Err(PathError::Shape(format!(
121            "${{{path}[{key}]}}: string key on a list — use an integer index"
122        ))),
123        _ => unreachable!("resolve_step guards non-collection containers"),
124    }
125}
126
127/// Classify a slice against an array, end-exclusive. Bounds clamp; negatives
128/// count from the end; an inverted or empty range yields an empty range.
129/// Slicing a record is an error.
130fn classify_slice(
131    json: &serde_json::Value,
132    start: Option<i64>,
133    end: Option<i64>,
134    path: &str,
135) -> Result<Step, PathError> {
136    // A string slices by CHARACTERS, not bytes: kaish refuses lossy text
137    // everywhere else, and a byte range can split a multi-byte sequence.
138    let len = match json {
139        serde_json::Value::Array(a) => a.len() as i64,
140        serde_json::Value::String(s) => s.chars().count() as i64,
141        serde_json::Value::Object(_) => {
142            return Err(PathError::Shape(format!(
143                "${{{path}[..]}}: cannot slice a record"
144            )))
145        }
146        _ => unreachable!("resolve_step guards non-sliceable containers"),
147    };
148    let norm = |b: i64| -> i64 {
149        let b = if b < 0 { len + b } else { b };
150        b.clamp(0, len)
151    };
152    let s = start.map(norm).unwrap_or(0);
153    let e = end.map(norm).unwrap_or(len);
154    let (s, e) = if s >= e {
155        (s as usize, s as usize)
156    } else {
157        (s as usize, e as usize)
158    };
159    Ok(Step::Slice(s, e))
160}
161
162/// A dotted `.field` access. Brackets-only: always a loud error, with the
163/// bracket fix in the message. Shared by the root pre-check and `resolve_step`
164/// so a dotted segment reports identically at any hop.
165fn dotted_access_error(path: &str, field: &str) -> PathError {
166    PathError::Shape(format!(
167        "${{{path}…}}: kaish uses bracket access, not dots — write the key as a subscript: [{field}]"
168    ))
169}
170
171/// Render a subscript as the user wrote it, for building the path prefix that
172/// error messages carry (`a` → `a[b]` → `a[b][0]`) so a nested failure names the
173/// real path, not just the root.
174fn render_segment(seg: &VarSegment) -> String {
175    match seg {
176        VarSegment::Index(i) => format!("[{i}]"),
177        VarSegment::Key(k) => format!("[{k}]"),
178        VarSegment::Dynamic(v) => format!("[${v}]"),
179        VarSegment::Slice(a, b) => format!(
180            "[{}:{}]",
181            a.map(|n| n.to_string()).unwrap_or_default(),
182            b.map(|n| n.to_string()).unwrap_or_default()
183        ),
184        VarSegment::Field(f) => format!(".{f}"),
185    }
186}
187
188/// Classify one subscript against its container — the shared per-hop unit that
189/// keeps read traversal and (next phase) lvalue writes from diverging. Only the
190/// dynamic-key arm needs the scope (to look up `$k`); everything else is a pure
191/// function of the container and segment. A non-collection container is caught
192/// here once, so the `classify_*` helpers never see a scalar.
193fn resolve_step(
194    container: &serde_json::Value,
195    seg: &VarSegment,
196    scope: &Scope,
197    path: &str,
198) -> Result<Step, PathError> {
199    // A non-root `Field` is a dotted `.field` access — checked before the
200    // container guard so a dotted segment always wins over a "not a collection"
201    // message (the per-hop precedence the old walker had).
202    if let VarSegment::Field(name) = seg {
203        return Err(dotted_access_error(path, name));
204    }
205
206    // A string is sliceable but not indexable. `${s[0:5]}` is the first five
207    // characters; `${s[0]}` has no meaning kaish defines, since an index picks
208    // an element and a string has no elements. The error says which is which
209    // rather than only refusing.
210    if matches!(container, serde_json::Value::String(_)) {
211        return match seg {
212            VarSegment::Slice(start, end) => classify_slice(container, *start, *end, path),
213            _ => Err(PathError::Shape(format!(
214                "${{{path}…}}: cannot subscript a string — slice it instead, \
215                 e.g. ${{{path}[0:5]}} for the first five characters"
216            ))),
217        };
218    }
219
220    // Every remaining subscript needs a collection container.
221    if !matches!(
222        container,
223        serde_json::Value::Array(_) | serde_json::Value::Object(_)
224    ) {
225        return Err(PathError::Shape(format!(
226            "${{{path}…}}: cannot subscript {} — it is not a collection",
227            type_name(&json_to_value_no_envelope(container.clone()))
228        )));
229    }
230
231    match seg {
232        VarSegment::Index(i) => classify_index(container, *i, path),
233        VarSegment::Key(k) => classify_key(container, k, path),
234        VarSegment::Slice(start, end) => classify_slice(container, *start, *end, path),
235        VarSegment::Dynamic(var) => {
236            // The variable's value is the subscript; the container type decides
237            // whether it's an index or a key. An unset `$k` is UndefinedRoot,
238            // not Absence — the *variable* is missing, so `${r[$k]:-d}` defaults.
239            let key_val = scope.get(var).ok_or_else(|| {
240                PathError::UndefinedRoot(format!("${{{path}[${var}]}}: ${var} is not set"))
241            })?;
242            match container {
243                serde_json::Value::Array(_) => {
244                    let idx = value_as_index(key_val).ok_or_else(|| {
245                        PathError::Shape(format!(
246                            "${{{path}[${var}]}}: a list index must be an integer, got \"{}\"",
247                            value_to_string(key_val)
248                        ))
249                    })?;
250                    classify_index(container, idx, path)
251                }
252                serde_json::Value::Object(_) => Ok(Step::Key(value_to_string(key_val))),
253                _ => unreachable!("non-collection container guarded above"),
254            }
255        }
256        VarSegment::Field(_) => unreachable!("dotted segment handled above"),
257    }
258}
259
260/// Apply one classified step, descending the borrowed JSON tree. Borrowed input
261/// stays borrowed for index/key (no clone); a slice always allocates a new list,
262/// and once owned (post-slice) descent clones the selected child. A missing
263/// record key is a loud read error here — the write-leaf insert is the next
264/// phase, and lives in the walk, not in [`resolve_step`].
265fn descend<'a>(
266    current: Cow<'a, serde_json::Value>,
267    step: Step,
268    path: &str,
269) -> Result<Cow<'a, serde_json::Value>, PathError> {
270    match step {
271        Step::Slice(s, e) => match current.as_ref() {
272            serde_json::Value::Array(arr) => {
273                Ok(Cow::Owned(serde_json::Value::Array(arr[s..e].to_vec())))
274            }
275            // Char-indexed, matching `classify_slice`'s char-based bounds.
276            serde_json::Value::String(text) => Ok(Cow::Owned(serde_json::Value::String(
277                text.chars().skip(s).take(e - s).collect(),
278            ))),
279            _ => unreachable!("slice classified against an array or string"),
280        },
281        Step::Index(i) => match current {
282            Cow::Borrowed(j) => {
283                let Some(arr) = j.as_array() else {
284                    unreachable!("index classified against an array")
285                };
286                Ok(Cow::Borrowed(&arr[i]))
287            }
288            Cow::Owned(j) => {
289                let Some(arr) = j.as_array() else {
290                    unreachable!("index classified against an array")
291                };
292                Ok(Cow::Owned(arr[i].clone()))
293            }
294        },
295        Step::Key(k) => match current {
296            Cow::Borrowed(j) => match j.as_object().and_then(|m| m.get(&k)) {
297                Some(child) => Ok(Cow::Borrowed(child)),
298                None => Err(PathError::Absence(format!("${{{path}[{k}]}}: no such key"))),
299            },
300            Cow::Owned(j) => match j.as_object().and_then(|m| m.get(&k)) {
301                Some(child) => Ok(Cow::Owned(child.clone())),
302                None => Err(PathError::Absence(format!("${{{path}[{k}]}}: no such key"))),
303            },
304        },
305    }
306}
307
308/// Apply one classified step during a **write** walk's intermediate hops:
309/// descend mutably, requiring the child to already exist — no
310/// autovivification. Bounds/shape were already checked by `resolve_step`;
311/// this only adds the "must already exist" policy that only a write walk
312/// needs (a read's `descend` also requires existence for `Key`, but a write's
313/// *final* hop diverges — see `apply_leaf_write`). A `Slice` step can never
314/// be part of a valid lvalue path (mutating through a detached slice copy
315/// wouldn't write back), so it is always a loud `Shape` error here,
316/// intermediate or not.
317fn descend_mut<'a>(
318    current: &'a mut serde_json::Value,
319    step: Step,
320    path: &str,
321) -> Result<&'a mut serde_json::Value, PathError> {
322    match step {
323        Step::Slice(..) => Err(PathError::Shape(format!(
324            "${{{path}[..]}}: slice lvalues are not supported — index or key paths only"
325        ))),
326        Step::Index(i) => {
327            let Some(arr) = current.as_array_mut() else {
328                unreachable!("index classified against an array")
329            };
330            Ok(&mut arr[i])
331        }
332        Step::Key(k) => {
333            let Some(map) = current.as_object_mut() else {
334                unreachable!("key classified against an object")
335            };
336            match map.get_mut(&k) {
337                Some(child) => Ok(child),
338                None => Err(PathError::Absence(format!(
339                    "${{{path}[{k}]}}: no such key — no autovivification, create it first (e.g. `{path}[{k}]={{}}`)"
340                ))),
341            }
342        }
343    }
344}
345
346/// Apply the classified **final** step of a write walk: a record key inserts
347/// or updates (the one thing a path-set may create), a list index updates
348/// in-bounds (already validated by `resolve_step`'s `classify_index` — an
349/// out-of-bounds index is an `Absence` error before this is ever reached),
350/// and a slice is a loud `Shape` error (no slice lvalues — `push` grows
351/// lists).
352fn apply_leaf_write(
353    current: &mut serde_json::Value,
354    step: Step,
355    value: serde_json::Value,
356    path: &str,
357) -> Result<(), PathError> {
358    match step {
359        Step::Slice(..) => Err(PathError::Shape(format!(
360            "${{{path}[..]}}: slice lvalues are not supported — index or key paths only"
361        ))),
362        Step::Index(i) => {
363            let Some(arr) = current.as_array_mut() else {
364                unreachable!("index classified against an array")
365            };
366            arr[i] = value;
367            Ok(())
368        }
369        Step::Key(k) => {
370            let Some(map) = current.as_object_mut() else {
371                unreachable!("key classified against an object")
372            };
373            map.insert(k, value);
374            Ok(())
375        }
376    }
377}
378
379/// Render a mid-walk `PathError` for `push`'s error text. `Absence`/`Shape`
380/// already carry a ready-to-display `${…}` message from `resolve_step`/
381/// `descend_mut` (shared with `walk_write`); only `UndefinedRoot` needs
382/// `push`-flavored wording here — it fires for an unset `$k` dynamic
383/// subscript mid-path, not the root itself (`walk_append` checks the root
384/// exists before ever starting the walk).
385fn push_path_error_message(err: PathError, root_name: &str) -> String {
386    match err {
387        PathError::UndefinedRoot(msg) if msg.is_empty() => {
388            format!("push: {root_name} is not defined")
389        }
390        PathError::UndefinedRoot(msg) => format!("push: {msg}"),
391        PathError::Absence(msg) | PathError::Shape(msg) => msg,
392    }
393}
394
395/// Variable scope with nested frames and last-result tracking.
396///
397/// Variables are looked up from innermost to outermost frame.
398/// The `?` variable always refers to the last command result.
399///
400/// The `frames` field is wrapped in `Arc` for copy-on-write (COW) semantics.
401/// Cloning a Scope is O(1) — just bumps the Arc refcount. Mutations use
402/// `Arc::make_mut` to clone the inner data only when shared. This matters
403/// because `execute_pipeline` snapshots the scope into ExecContext (clone)
404/// and syncs it back (clone) on every command.
405#[derive(Debug, Clone)]
406pub struct Scope {
407    /// Stack of variable frames. Last element is the innermost scope.
408    /// Wrapped in Arc for copy-on-write: clone is O(1), mutation clones on demand.
409    frames: Arc<Vec<HashMap<String, Value>>>,
410    /// Variables marked for export to child processes.
411    exported: HashSet<String>,
412    /// The result of the last command execution.
413    ///
414    /// Boxed: `Scope` is cloned/held by value at every recursion level (the
415    /// dispatch snapshot, the command-subst save/restore), and an inline
416    /// `ExecResult` made `Scope` ~half again as large in each of those copies
417    /// (GH #48, item 5). The box is reused in place by `set_last_result`, so the
418    /// steady state is one allocation per `Scope`, not one per update.
419    last_result: Box<ExecResult>,
420    /// Script or tool name ($0).
421    script_name: String,
422    /// Positional arguments ($1-$9, $@, $#).
423    positional: Vec<String>,
424    /// Error exit mode (set -e): exit on any command failure.
425    error_exit: bool,
426    /// Counter for temporarily suppressing errexit (e.g. inside && / || left side).
427    /// When > 0, error_exit_enabled() returns false even if error_exit is true.
428    errexit_suppressed: usize,
429    /// AST display mode (kaish-ast -on/-off): show AST instead of executing.
430    show_ast: bool,
431    /// Trash mode (set -o trash): move deleted files to freedesktop.org Trash.
432    trash_enabled: bool,
433    /// Maximum file size (bytes) for trash. Files larger than this bypass trash.
434    /// Default: 10 MB.
435    trash_max_size: u64,
436    /// Glob expansion mode (set -o glob): expand bare glob patterns in arguments.
437    glob_enabled: bool,
438    /// Kaish session identifier ($$). A monotonic counter assigned at Kernel
439    /// construction (see `KERNEL_COUNTER` in kernel.rs) — *not* the OS PID.
440    /// Subshells / forks inherit the parent's value (Scope clone copies it).
441    /// 0 is a sentinel meaning "this scope was constructed outside a Kernel"
442    /// (e.g. arithmetic unit tests, kaish-clear before its setter runs).
443    pid: u64,
444}
445
446impl Scope {
447    /// Create a new scope with one empty frame.
448    ///
449    /// `pid` defaults to 0 (sentinel). The owning Kernel calls `set_pid()`
450    /// during construction to assign the real session identifier.
451    pub fn new() -> Self {
452        Self {
453            frames: Arc::new(vec![HashMap::new()]),
454            exported: HashSet::new(),
455            last_result: Box::new(ExecResult::default()),
456            script_name: String::new(),
457            positional: Vec::new(),
458            error_exit: false,
459            errexit_suppressed: 0,
460            show_ast: false,
461            trash_enabled: false,
462            trash_max_size: 10 * 1024 * 1024, // 10 MB
463            glob_enabled: true,
464            pid: 0,
465        }
466    }
467
468    /// Get the kaish session identifier ($$).
469    pub fn pid(&self) -> u64 {
470        self.pid
471    }
472
473    /// Set the kaish session identifier ($$). Called by the Kernel during
474    /// construction to thread the assigned counter value into the scope.
475    /// Also used by `kaish-clear` to preserve $$ across a session reset.
476    pub fn set_pid(&mut self, pid: u64) {
477        self.pid = pid;
478    }
479
480    /// Push a new scope frame (for entering a loop, tool call, etc.)
481    pub fn push_frame(&mut self) {
482        Arc::make_mut(&mut self.frames).push(HashMap::new());
483    }
484
485    /// Pop the innermost scope frame.
486    ///
487    /// Panics if attempting to pop the last frame.
488    pub fn pop_frame(&mut self) {
489        if self.frames.len() > 1 {
490            Arc::make_mut(&mut self.frames).pop();
491        } else {
492            panic!("cannot pop the root scope frame");
493        }
494    }
495
496    /// Set a variable in the current (innermost) frame.
497    ///
498    /// Use this for `local` variable declarations.
499    pub fn set(&mut self, name: impl Into<String>, value: Value) {
500        if let Some(frame) = Arc::make_mut(&mut self.frames).last_mut() {
501            frame.insert(name.into(), value);
502        }
503    }
504
505    /// Set a variable with global semantics (shell default).
506    ///
507    /// If the variable exists in any frame, update it there.
508    /// Otherwise, create it in the outermost (root) frame.
509    /// Use this for non-local variable assignments.
510    pub fn set_global(&mut self, name: impl Into<String>, value: Value) {
511        let name = name.into();
512
513        // Search from innermost to outermost to find existing variable
514        let frames = Arc::make_mut(&mut self.frames);
515        for frame in frames.iter_mut().rev() {
516            if let std::collections::hash_map::Entry::Occupied(mut e) = frame.entry(name.clone()) {
517                e.insert(value);
518                return;
519            }
520        }
521
522        // Variable doesn't exist - create in root frame (index 0)
523        if let Some(frame) = frames.first_mut() {
524            frame.insert(name, value);
525        }
526    }
527
528    /// Get a variable by name, searching from innermost to outermost frame.
529    pub fn get(&self, name: &str) -> Option<&Value> {
530        for frame in self.frames.iter().rev() {
531            if let Some(value) = frame.get(name) {
532                return Some(value);
533            }
534        }
535        None
536    }
537
538    /// Remove a variable, searching from innermost to outermost frame.
539    ///
540    /// Returns the removed value if found, None otherwise.
541    pub fn remove(&mut self, name: &str) -> Option<Value> {
542        for frame in Arc::make_mut(&mut self.frames).iter_mut().rev() {
543            if let Some(value) = frame.remove(name) {
544                return Some(value);
545            }
546        }
547        None
548    }
549
550    /// Set the last command result (accessible via `$?`).
551    pub fn set_last_result(&mut self, result: ExecResult) {
552        // Write through the existing box rather than reallocating one.
553        *self.last_result = result;
554    }
555
556    /// Get the last command result.
557    pub fn last_result(&self) -> &ExecResult {
558        &self.last_result
559    }
560
561    /// Set the positional parameters ($0, $1-$9, $@, $#).
562    ///
563    /// The script_name becomes $0, and args become $1, $2, etc.
564    pub fn set_positional(&mut self, script_name: impl Into<String>, args: Vec<String>) {
565        self.script_name = script_name.into();
566        self.positional = args;
567    }
568
569    /// Save current positional parameters for later restoration.
570    ///
571    /// Returns (script_name, args) tuple that can be passed to set_positional.
572    pub fn save_positional(&self) -> (String, Vec<String>) {
573        (self.script_name.clone(), self.positional.clone())
574    }
575
576    /// Get a positional parameter by index ($0-$9).
577    ///
578    /// $0 returns the script name, $1-$9 return arguments.
579    pub fn get_positional(&self, n: usize) -> Option<&str> {
580        if n == 0 {
581            if self.script_name.is_empty() {
582                None
583            } else {
584                Some(&self.script_name)
585            }
586        } else {
587            self.positional.get(n - 1).map(|s| s.as_str())
588        }
589    }
590
591    /// Get all positional arguments as a slice ($@).
592    pub fn all_args(&self) -> &[String] {
593        &self.positional
594    }
595
596    /// Get the count of positional arguments ($#).
597    pub fn arg_count(&self) -> usize {
598        self.positional.len()
599    }
600
601    /// Check if error-exit mode is active (set -e and not suppressed).
602    ///
603    /// Returns false when inside the left side of `&&` or `||` chains,
604    /// matching bash behavior where those operators handle failure themselves.
605    pub fn error_exit_enabled(&self) -> bool {
606        self.error_exit && self.errexit_suppressed == 0
607    }
608
609    /// Set error-exit mode (set -e / set +e).
610    pub fn set_error_exit(&mut self, enabled: bool) {
611        self.error_exit = enabled;
612    }
613
614    /// Suppress errexit temporarily (for `&&`/`||` left side).
615    pub fn suppress_errexit(&mut self) {
616        self.errexit_suppressed += 1;
617    }
618
619    /// Unsuppress errexit (after `&&`/`||` left side completes).
620    pub fn unsuppress_errexit(&mut self) {
621        self.errexit_suppressed = self.errexit_suppressed.saturating_sub(1);
622    }
623
624    /// Check if AST display mode is enabled (kaish-ast -on).
625    pub fn show_ast(&self) -> bool {
626        self.show_ast
627    }
628
629    /// Set AST display mode (kaish-ast -on / kaish-ast -off).
630    pub fn set_show_ast(&mut self, enabled: bool) {
631        self.show_ast = enabled;
632    }
633
634    /// Check if trash mode is enabled (set -o trash).
635    pub fn trash_enabled(&self) -> bool {
636        self.trash_enabled
637    }
638
639    /// Set trash mode (set -o trash / set +o trash).
640    pub fn set_trash_enabled(&mut self, enabled: bool) {
641        self.trash_enabled = enabled;
642    }
643
644    /// Get the maximum file size for trash (bytes).
645    pub fn trash_max_size(&self) -> u64 {
646        self.trash_max_size
647    }
648
649    /// Set the maximum file size for trash (bytes).
650    pub fn set_trash_max_size(&mut self, size: u64) {
651        self.trash_max_size = size;
652    }
653
654    /// Check if glob expansion is enabled (set -o glob, default true).
655    pub fn glob_enabled(&self) -> bool {
656        self.glob_enabled
657    }
658
659    /// Set glob expansion mode (set -o glob / set +o glob).
660    pub fn set_glob_enabled(&mut self, enabled: bool) {
661        self.glob_enabled = enabled;
662    }
663
664    /// Mark a variable as exported (visible to child processes).
665    ///
666    /// The variable doesn't need to exist yet; it will be exported when set.
667    pub fn export(&mut self, name: impl Into<String>) {
668        self.exported.insert(name.into());
669    }
670
671    /// Check if a variable is marked for export.
672    pub fn is_exported(&self, name: &str) -> bool {
673        self.exported.contains(name)
674    }
675
676    /// Set a variable in the **innermost** frame and mark it as exported.
677    ///
678    /// Used for frame-scoped overlays (`execute_with_vars`, `FOO=bar cmd`) and
679    /// for seeding root-frame exports at construction. For the `export`
680    /// builtin's assignment form use [`set_exported_global`](Self::set_exported_global)
681    /// so the value survives a function return (shared-scope semantics).
682    pub fn set_exported(&mut self, name: impl Into<String>, value: Value) {
683        let name = name.into();
684        self.set(&name, value);
685        self.export(name);
686    }
687
688    /// Set a variable with **global** (shared-scope) semantics and mark it as
689    /// exported. This is `export NAME=VALUE`: like a plain assignment, the value
690    /// updates an existing variable wherever it lives or lands in the root frame,
691    /// so it persists past a function return rather than dying with the
692    /// function's frame.
693    pub fn set_exported_global(&mut self, name: impl Into<String>, value: Value) {
694        let name = name.into();
695        self.set_global(&name, value);
696        self.export(name);
697    }
698
699    /// Unmark a variable from export.
700    pub fn unexport(&mut self, name: &str) {
701        self.exported.remove(name);
702    }
703
704    /// Get all exported variables with their values.
705    ///
706    /// Only returns variables that exist and are marked for export.
707    pub fn exported_vars(&self) -> Vec<(String, Value)> {
708        let mut result = Vec::new();
709        for name in &self.exported {
710            if let Some(value) = self.get(name) {
711                result.push((name.clone(), value.clone()));
712            }
713        }
714        result.sort_by(|(a, _), (b, _)| a.cmp(b));
715        result
716    }
717
718    /// Get all exported variable names.
719    pub fn exported_names(&self) -> Vec<&str> {
720        let mut names: Vec<&str> = self.exported.iter().map(|s| s.as_str()).collect();
721        names.sort();
722        names
723    }
724
725    /// Resolve a variable path: `${VAR}`, `${xs[0]}`, `${r[key]}`, `${a[b][c]}`.
726    ///
727    /// The first segment is the root name; the rest are bracket subscripts,
728    /// walked left to right into the root's `Value::Json`. A subscript landing
729    /// on a JSON scalar unwraps to a native `Value` (envelope-free); a subscript
730    /// landing on a collection stays `Value::Json`. `$?` resolves to the
731    /// previous command's exit code (bare only).
732    ///
733    /// Traversal borrows into the root's JSON tree and clones only the selected
734    /// leaf (a slice builds a new list); the whole-root clone is never taken, so
735    /// repeated `${u[$k]}` in a loop stays O(depth), not O(root size). The
736    /// per-hop classification lives in `resolve_step`, shared with the future
737    /// lvalue-write walk so read and write can never diverge.
738    ///
739    /// Errors distinguish an undefined root (soft) from a loud path error (see
740    /// [`PathError`]).
741    pub fn resolve_path(&self, path: &VarPath) -> Result<Value, PathError> {
742        let Some(VarSegment::Field(root_name)) = path.segments.first() else {
743            // Empty path, or a first segment the parser never emits as root.
744            return Err(PathError::UndefinedRoot(String::new()));
745        };
746
747        // Special case: $? (last result) — bare only.
748        if root_name == "?" {
749            if path.segments.len() == 1 {
750                return Ok(Value::Int(self.last_result.code));
751            }
752            return Err(PathError::Shape(
753                "$? is the POSIX exit code, not a collection — use `kaish-last` for structured data"
754                    .to_string(),
755            ));
756        }
757
758        let root = self
759            .get(root_name)
760            .ok_or_else(|| PathError::UndefinedRoot(root_name.clone()))?;
761
762        // Bare `${VAR}`: return the stored value unchanged — no subscript, no
763        // envelope unwrap.
764        let subscripts = &path.segments[1..];
765        if subscripts.is_empty() {
766            return Ok(root.clone());
767        }
768
769        // A leading dotted segment is brackets-only regardless of the root's
770        // type (matches the per-hop Field-before-container precedence in
771        // `resolve_step`, which the root-collection check below would otherwise
772        // preempt on a scalar root).
773        if let Some(VarSegment::Field(name)) = subscripts.first() {
774            return Err(dotted_access_error(root_name, name));
775        }
776
777        // Subscripted: the root must be a collection to descend into — or a
778        // string, which is sliceable (`${s[0:5]}`) though not indexable. A
779        // native `Value::String` root is lifted into JSON here so the one walk
780        // handles both; `resolve_step` then decides slice-versus-index and
781        // owns the message. Any other scalar reports the same "not a
782        // collection" message a mid-path scalar would.
783        let lifted;
784        let root_json = match root {
785            Value::Json(j) => j,
786            Value::String(s) => {
787                lifted = serde_json::Value::String(s.clone());
788                &lifted
789            }
790            other => {
791                return Err(PathError::Shape(format!(
792                    "${{{root_name}…}}: cannot subscript {} — it is not a collection",
793                    type_name(other)
794                )))
795            }
796        };
797
798        // Walk the subscripts, borrowing into the tree; only a slice (which
799        // builds a new list) and the terminal unwrap allocate. `prefix`
800        // accumulates the path walked so far so a nested failure names the real
801        // path (`${a[b][9]}`, not `${a[9]}`).
802        let mut current = Cow::Borrowed(root_json);
803        let mut prefix = root_name.clone();
804        for seg in subscripts {
805            let step = resolve_step(&current, seg, self, &prefix)?;
806            current = descend(current, step, &prefix)?;
807            prefix.push_str(&render_segment(seg));
808        }
809        Ok(json_to_value_no_envelope(current.into_owned()))
810    }
811
812    /// Write a value into a collection lvalue path: `xs[0]=9`,
813    /// `user[email]=amy@example.com`, `services[web][port]=9090`.
814    ///
815    /// Shares `resolve_step` with [`resolve_path`](Self::resolve_path) so
816    /// classification (bounds, shape) never drifts between read and write.
817    /// The walk itself diverges at the leaf: every intermediate hop requires
818    /// the child to already exist (`descend_mut` — **no autovivification**),
819    /// while the final hop may insert a new record key (`apply_leaf_write`) —
820    /// the ONLY thing a path-set may create. A list index write is in-bounds
821    /// update only (`resolve_step`'s `classify_index` already turns an
822    /// out-of-bounds index into a loud `Absence`); `push` is how lists grow.
823    /// A slice lvalue (`xs[0:2]=…`) is always a `Shape` error.
824    ///
825    /// The root must already be defined (`UndefinedRoot`) and be a collection
826    /// (`Shape` for a scalar root) — same rule as a read. On success the
827    /// mutated root replaces the old value via `set_global`. A bracket-path
828    /// write updates the variable wherever it lives and ignores `local`,
829    /// because it mutates an existing binding instead of creating one. See
830    /// `docs/LANGUAGE.md`, "Assignment — bracket-path lvalues".
831    pub fn walk_write(&mut self, path: &VarPath, value: Value) -> Result<(), PathError> {
832        let Some(VarSegment::Field(root_name)) = path.segments.first() else {
833            return Err(PathError::UndefinedRoot(String::new()));
834        };
835
836        let root = self
837            .get(root_name)
838            .ok_or_else(|| PathError::UndefinedRoot(root_name.clone()))?;
839
840        let mut root_json = match root {
841            Value::Json(j) => j.clone(),
842            other => {
843                return Err(PathError::Shape(format!(
844                    "${{{root_name}…}}: cannot subscript {} — it is not a collection",
845                    type_name(other)
846                )))
847            }
848        };
849
850        let subscripts = &path.segments[1..];
851        let Some((last, intermediates)) = subscripts.split_last() else {
852            // A bare name never reaches walk_write — the kernel routes a
853            // one-segment path through set/set_global. Guard defensively
854            // rather than silently no-op.
855            return Err(PathError::Shape(format!(
856                "{root_name}: assignment target has no subscript"
857            )));
858        };
859
860        let mut current = &mut root_json;
861        let mut prefix = root_name.clone();
862        for seg in intermediates {
863            let step = resolve_step(current, seg, self, &prefix)?;
864            current = descend_mut(current, step, &prefix)?;
865            prefix.push_str(&render_segment(seg));
866        }
867
868        let step = resolve_step(current, last, self, &prefix)?;
869        apply_leaf_write(current, step, value_to_json(&value), &prefix)?;
870
871        self.set_global(root_name.clone(), Value::Json(root_json));
872        Ok(())
873    }
874
875    /// Append value(s) to a list variable, in place: a top-level bareword
876    /// target (`push xs val`) or a bracket-path target
877    /// (`push services[web][tags] item`).
878    ///
879    /// The target must already exist and be a list — an undefined root, a
880    /// non-list leaf, or a missing intermediate hop is a loud error, never a
881    /// silent create or autoviv. See `docs/LANGUAGE.md`, "Assignment —
882    /// bracket-path lvalues + `push`". Intermediate hops share `walk_write`'s
883    /// `resolve_step`/`descend_mut`, so a `push` path and an assignment path
884    /// classify identically. Only the final hop differs: it appends instead
885    /// of replacing.
886    pub fn walk_append(&mut self, path: &VarPath, values: Vec<Value>) -> Result<(), String> {
887        let Some(VarSegment::Field(root_name)) = path.segments.first() else {
888            return Err("push: target has no root".to_string());
889        };
890        let root_name = root_name.clone();
891        let current = self
892            .get(&root_name)
893            .ok_or_else(|| format!("push: {root_name} is not defined"))?
894            .clone();
895
896        let subscripts = &path.segments[1..];
897        if subscripts.is_empty() {
898            if !matches!(current, Value::Json(serde_json::Value::Array(_))) {
899                return Err(format!("push: {root_name} is not a list ({})", type_name(&current)));
900            }
901            let Value::Json(serde_json::Value::Array(mut arr)) = current else {
902                unreachable!("checked above")
903            };
904            arr.extend(values.iter().map(value_to_json));
905            self.set_global(root_name, Value::Json(serde_json::Value::Array(arr)));
906            return Ok(());
907        }
908
909        let mut root_json = match current {
910            Value::Json(j) => j,
911            other => {
912                return Err(format!(
913                    "push: {root_name}…: cannot subscript {} — it is not a collection",
914                    type_name(&other)
915                ))
916            }
917        };
918
919        // Walk every subscript — including the last — with the shared
920        // no-autoviv intermediate walker: the container the values append
921        // into must already exist, matching `walk_write`'s policy.
922        let mut cur = &mut root_json;
923        let mut prefix = root_name.clone();
924        for seg in subscripts {
925            let step = resolve_step(cur, seg, self, &prefix)
926                .map_err(|e| push_path_error_message(e, &root_name))?;
927            cur = descend_mut(cur, step, &prefix)
928                .map_err(|e| push_path_error_message(e, &root_name))?;
929            prefix.push_str(&render_segment(seg));
930        }
931
932        let serde_json::Value::Array(arr) = cur else {
933            return Err(format!(
934                "push: {prefix} is not a list ({})",
935                type_name(&json_to_value_no_envelope(cur.clone()))
936            ));
937        };
938        arr.extend(values.iter().map(value_to_json));
939        self.set_global(root_name, Value::Json(root_json));
940        Ok(())
941    }
942
943    /// Check if a variable exists in any frame.
944    pub fn contains(&self, name: &str) -> bool {
945        self.get(name).is_some()
946    }
947
948    /// Get all variable names in scope (for debugging/introspection).
949    pub fn all_names(&self) -> Vec<&str> {
950        let mut names: Vec<&str> = self
951            .frames
952            .iter()
953            .flat_map(|f| f.keys().map(|s| s.as_str()))
954            .collect();
955        names.sort();
956        names.dedup();
957        names
958    }
959
960    /// Get all variables as (name, value) pairs.
961    ///
962    /// Variables are deduplicated, with inner frames shadowing outer ones.
963    pub fn all(&self) -> Vec<(String, Value)> {
964        let mut result = std::collections::HashMap::new();
965        // Iterate outer to inner so inner frames override
966        for frame in self.frames.iter() {
967            for (name, value) in frame {
968                result.insert(name.clone(), value.clone());
969            }
970        }
971        let mut pairs: Vec<_> = result.into_iter().collect();
972        pairs.sort_by(|(a, _), (b, _)| a.cmp(b));
973        pairs
974    }
975}
976
977impl Default for Scope {
978    fn default() -> Self {
979        Self::new()
980    }
981}
982
983#[cfg(test)]
984mod tests {
985    use super::*;
986
987    #[test]
988    fn new_scope_has_one_frame() {
989        let scope = Scope::new();
990        assert_eq!(scope.frames.len(), 1);
991    }
992
993    #[test]
994    fn set_and_get_variable() {
995        let mut scope = Scope::new();
996        scope.set("X", Value::Int(42));
997        assert_eq!(scope.get("X"), Some(&Value::Int(42)));
998    }
999
1000    #[test]
1001    fn get_nonexistent_returns_none() {
1002        let scope = Scope::new();
1003        assert_eq!(scope.get("MISSING"), None);
1004    }
1005
1006    #[test]
1007    fn inner_frame_shadows_outer() {
1008        let mut scope = Scope::new();
1009        scope.set("X", Value::Int(1));
1010        scope.push_frame();
1011        scope.set("X", Value::Int(2));
1012        assert_eq!(scope.get("X"), Some(&Value::Int(2)));
1013        scope.pop_frame();
1014        assert_eq!(scope.get("X"), Some(&Value::Int(1)));
1015    }
1016
1017    #[test]
1018    fn inner_frame_can_see_outer_vars() {
1019        let mut scope = Scope::new();
1020        scope.set("OUTER", Value::String("visible".into()));
1021        scope.push_frame();
1022        assert_eq!(scope.get("OUTER"), Some(&Value::String("visible".into())));
1023    }
1024
1025    #[test]
1026    fn resolve_simple_path() {
1027        let mut scope = Scope::new();
1028        scope.set("NAME", Value::String("Alice".into()));
1029
1030        let path = VarPath::simple("NAME");
1031        assert_eq!(
1032            scope.resolve_path(&path),
1033            Ok(Value::String("Alice".into()))
1034        );
1035    }
1036
1037    #[test]
1038    fn resolve_bare_last_result_returns_exit_code() {
1039        let mut scope = Scope::new();
1040        scope.set_last_result(ExecResult::failure(127, "not found"));
1041
1042        let path = VarPath {
1043            segments: vec![VarSegment::Field("?".into())],
1044        };
1045        assert_eq!(scope.resolve_path(&path), Ok(Value::Int(127)));
1046    }
1047
1048    #[test]
1049    fn resolve_last_result_field_access_is_rejected() {
1050        // Field access on $? was removed — use `kaish-last` for structured data.
1051        // The resolver now returns a loud error; the validator also catches it
1052        // earlier with a specific error code for actionable diagnostics.
1053        let mut scope = Scope::new();
1054        scope.set_last_result(ExecResult::success_with_data(
1055            "1",
1056            Value::Json(serde_json::json!({"count": 5})),
1057        ));
1058
1059        let path = VarPath {
1060            segments: vec![
1061                VarSegment::Field("?".into()),
1062                VarSegment::Field("data".into()),
1063            ],
1064        };
1065        assert!(matches!(
1066            scope.resolve_path(&path),
1067            Err(PathError::Shape(_))
1068        ));
1069    }
1070
1071    #[test]
1072    fn resolve_dotted_access_on_scalar_is_a_loud_error() {
1073        let mut scope = Scope::new();
1074        scope.set("X", Value::Int(42));
1075
1076        // Dotted access `${X.invalid}` — brackets-only, so it's a loud error.
1077        let path = VarPath {
1078            segments: vec![
1079                VarSegment::Field("X".into()),
1080                VarSegment::Field("invalid".into()),
1081            ],
1082        };
1083        assert!(matches!(
1084            scope.resolve_path(&path),
1085            Err(PathError::Shape(_))
1086        ));
1087    }
1088
1089    #[test]
1090    fn resolve_undefined_root_is_soft() {
1091        let scope = Scope::new();
1092        let path = VarPath::simple("NOPE");
1093        assert!(matches!(
1094            scope.resolve_path(&path),
1095            Err(PathError::UndefinedRoot(_))
1096        ));
1097    }
1098
1099    // ── PathError classification (Absence vs Shape) ─────────────────────────
1100    // Pins the three-way split: `${path:-default}` (a later commit) leans on
1101    // Absence-vs-Shape, so a misclassification here is a real semantic bug, not
1102    // cosmetics. All three stay loud for a bare access.
1103
1104    /// Build `${root[seg]}` with one bracket subscript.
1105    fn subscripted(scope: &mut Scope, root: &str, value: serde_json::Value, seg: VarSegment) -> Result<Value, PathError> {
1106        scope.set(root, Value::Json(value));
1107        let path = VarPath {
1108            segments: vec![VarSegment::Field(root.into()), seg],
1109        };
1110        scope.resolve_path(&path)
1111    }
1112
1113    #[test]
1114    fn out_of_bounds_index_is_absence() {
1115        let mut scope = Scope::new();
1116        let r = subscripted(&mut scope, "xs", serde_json::json!([1, 2]), VarSegment::Index(9));
1117        assert!(matches!(r, Err(PathError::Absence(_))), "got: {r:?}");
1118    }
1119
1120    #[test]
1121    fn missing_record_key_is_absence() {
1122        let mut scope = Scope::new();
1123        let r = subscripted(&mut scope, "u", serde_json::json!({"name": "amy"}), VarSegment::Key("nope".into()));
1124        assert!(matches!(r, Err(PathError::Absence(_))), "got: {r:?}");
1125    }
1126
1127    #[test]
1128    fn string_key_on_a_list_is_shape() {
1129        let mut scope = Scope::new();
1130        let r = subscripted(&mut scope, "xs", serde_json::json!([1, 2]), VarSegment::Key("web".into()));
1131        assert!(matches!(r, Err(PathError::Shape(_))), "got: {r:?}");
1132    }
1133
1134    #[test]
1135    fn integer_index_on_a_record_is_shape() {
1136        let mut scope = Scope::new();
1137        let r = subscripted(&mut scope, "u", serde_json::json!({"name": "amy"}), VarSegment::Index(0));
1138        assert!(matches!(r, Err(PathError::Shape(_))), "got: {r:?}");
1139    }
1140
1141    #[test]
1142    fn subscripting_a_scalar_is_shape() {
1143        let mut scope = Scope::new();
1144        scope.set("s", Value::String("hello".into()));
1145        let path = VarPath {
1146            segments: vec![VarSegment::Field("s".into()), VarSegment::Index(0)],
1147        };
1148        assert!(matches!(scope.resolve_path(&path), Err(PathError::Shape(_))));
1149    }
1150
1151    #[test]
1152    fn unset_dynamic_key_is_undefined_root_not_absence() {
1153        // `${r[$k]}` with `$k` unset: the *variable* is missing, so it's
1154        // UndefinedRoot-class (which `:-` treats as absence), not a Shape error.
1155        let mut scope = Scope::new();
1156        let r = subscripted(
1157            &mut scope,
1158            "r",
1159            serde_json::json!({"name": "amy"}),
1160            VarSegment::Dynamic("k".into()),
1161        );
1162        assert!(matches!(r, Err(PathError::UndefinedRoot(_))), "got: {r:?}");
1163    }
1164
1165    #[test]
1166    fn contains_finds_variable() {
1167        let mut scope = Scope::new();
1168        scope.set("EXISTS", Value::Bool(true));
1169        assert!(scope.contains("EXISTS"));
1170        assert!(!scope.contains("MISSING"));
1171    }
1172
1173    #[test]
1174    fn all_names_lists_variables() {
1175        let mut scope = Scope::new();
1176        scope.set("A", Value::Int(1));
1177        scope.set("B", Value::Int(2));
1178        scope.push_frame();
1179        scope.set("C", Value::Int(3));
1180
1181        let names = scope.all_names();
1182        assert!(names.contains(&"A"));
1183        assert!(names.contains(&"B"));
1184        assert!(names.contains(&"C"));
1185    }
1186
1187    #[test]
1188    #[should_panic(expected = "cannot pop the root scope frame")]
1189    fn pop_root_frame_panics() {
1190        let mut scope = Scope::new();
1191        scope.pop_frame();
1192    }
1193
1194    #[test]
1195    fn positional_params_basic() {
1196        let mut scope = Scope::new();
1197        scope.set_positional("my_tool", vec!["arg1".into(), "arg2".into(), "arg3".into()]);
1198
1199        // $0 is the script/tool name
1200        assert_eq!(scope.get_positional(0), Some("my_tool"));
1201        // $1, $2, $3 are the arguments
1202        assert_eq!(scope.get_positional(1), Some("arg1"));
1203        assert_eq!(scope.get_positional(2), Some("arg2"));
1204        assert_eq!(scope.get_positional(3), Some("arg3"));
1205        // $4 doesn't exist
1206        assert_eq!(scope.get_positional(4), None);
1207    }
1208
1209    #[test]
1210    fn positional_params_empty() {
1211        let scope = Scope::new();
1212        // No positional params set
1213        assert_eq!(scope.get_positional(0), None);
1214        assert_eq!(scope.get_positional(1), None);
1215        assert_eq!(scope.arg_count(), 0);
1216        assert!(scope.all_args().is_empty());
1217    }
1218
1219    #[test]
1220    fn all_args_returns_slice() {
1221        let mut scope = Scope::new();
1222        scope.set_positional("test", vec!["a".into(), "b".into(), "c".into()]);
1223
1224        let args = scope.all_args();
1225        assert_eq!(args, &["a", "b", "c"]);
1226    }
1227
1228    #[test]
1229    fn arg_count_returns_count() {
1230        let mut scope = Scope::new();
1231        scope.set_positional("test", vec!["one".into(), "two".into()]);
1232
1233        assert_eq!(scope.arg_count(), 2);
1234    }
1235
1236    #[test]
1237    fn export_marks_variable() {
1238        let mut scope = Scope::new();
1239        scope.set("X", Value::Int(42));
1240
1241        assert!(!scope.is_exported("X"));
1242        scope.export("X");
1243        assert!(scope.is_exported("X"));
1244    }
1245
1246    #[test]
1247    fn set_exported_sets_and_exports() {
1248        let mut scope = Scope::new();
1249        scope.set_exported("PATH", Value::String("/usr/bin".into()));
1250
1251        assert!(scope.is_exported("PATH"));
1252        assert_eq!(scope.get("PATH"), Some(&Value::String("/usr/bin".into())));
1253    }
1254
1255    #[test]
1256    fn unexport_removes_export_marker() {
1257        let mut scope = Scope::new();
1258        scope.set_exported("VAR", Value::Int(1));
1259        assert!(scope.is_exported("VAR"));
1260
1261        scope.unexport("VAR");
1262        assert!(!scope.is_exported("VAR"));
1263        // Variable still exists, just not exported
1264        assert!(scope.get("VAR").is_some());
1265    }
1266
1267    #[test]
1268    fn exported_vars_returns_only_exported_with_values() {
1269        let mut scope = Scope::new();
1270        scope.set_exported("A", Value::Int(1));
1271        scope.set_exported("B", Value::Int(2));
1272        scope.set("C", Value::Int(3)); // Not exported
1273        scope.export("D"); // Exported but no value
1274
1275        let exported = scope.exported_vars();
1276        assert_eq!(exported.len(), 2);
1277        assert_eq!(exported[0], ("A".to_string(), Value::Int(1)));
1278        assert_eq!(exported[1], ("B".to_string(), Value::Int(2)));
1279    }
1280
1281    #[test]
1282    fn exported_names_returns_sorted_names() {
1283        let mut scope = Scope::new();
1284        scope.export("Z");
1285        scope.export("A");
1286        scope.export("M");
1287
1288        let names = scope.exported_names();
1289        assert_eq!(names, vec!["A", "M", "Z"]);
1290    }
1291
1292    // ── walk_write (lvalue assignment) ──────────────────────────────────────
1293
1294    /// Build `xs[seg]=value` and apply it.
1295    fn write_at(
1296        scope: &mut Scope,
1297        root: &str,
1298        segs: Vec<VarSegment>,
1299    ) -> Result<(), PathError> {
1300        let mut segments = vec![VarSegment::Field(root.into())];
1301        segments.extend(segs);
1302        scope.walk_write(&VarPath { segments }, Value::Int(0))
1303    }
1304
1305    #[test]
1306    fn walk_write_list_index_update() {
1307        let mut scope = Scope::new();
1308        scope.set("xs", Value::Json(serde_json::json!([1, 2, 3])));
1309        let path = VarPath {
1310            segments: vec![VarSegment::Field("xs".into()), VarSegment::Index(0)],
1311        };
1312        scope.walk_write(&path, Value::Int(9)).expect("write should succeed");
1313        assert_eq!(scope.get("xs"), Some(&Value::Json(serde_json::json!([9, 2, 3]))));
1314    }
1315
1316    #[test]
1317    fn walk_write_negative_index() {
1318        let mut scope = Scope::new();
1319        scope.set("xs", Value::Json(serde_json::json!([1, 2, 3])));
1320        let path = VarPath {
1321            segments: vec![VarSegment::Field("xs".into()), VarSegment::Index(-1)],
1322        };
1323        scope.walk_write(&path, Value::Int(7)).expect("write should succeed");
1324        assert_eq!(scope.get("xs"), Some(&Value::Json(serde_json::json!([1, 2, 7]))));
1325    }
1326
1327    #[test]
1328    fn walk_write_inserts_a_new_record_key() {
1329        let mut scope = Scope::new();
1330        scope.set("u", Value::Json(serde_json::json!({"port": 8080})));
1331        let path = VarPath {
1332            segments: vec![VarSegment::Field("u".into()), VarSegment::Key("host".into())],
1333        };
1334        scope
1335            .walk_write(&path, Value::String("localhost".into()))
1336            .expect("write should succeed");
1337        assert_eq!(
1338            scope.get("u"),
1339            Some(&Value::Json(serde_json::json!({"port": 8080, "host": "localhost"})))
1340        );
1341    }
1342
1343    #[test]
1344    fn walk_write_deep_path_updates_nested_key() {
1345        let mut scope = Scope::new();
1346        scope.set("s", Value::Json(serde_json::json!({"web": {"port": 8080}})));
1347        let path = VarPath {
1348            segments: vec![
1349                VarSegment::Field("s".into()),
1350                VarSegment::Key("web".into()),
1351                VarSegment::Key("port".into()),
1352            ],
1353        };
1354        scope.walk_write(&path, Value::Int(9000)).expect("write should succeed");
1355        assert_eq!(
1356            scope.get("s"),
1357            Some(&Value::Json(serde_json::json!({"web": {"port": 9000}})))
1358        );
1359    }
1360
1361    #[test]
1362    fn walk_write_out_of_bounds_index_is_absence() {
1363        let mut scope = Scope::new();
1364        scope.set("xs", Value::Json(serde_json::json!([1, 2, 3])));
1365        let r = write_at(&mut scope, "xs", vec![VarSegment::Index(9)]);
1366        assert!(matches!(r, Err(PathError::Absence(_))), "got: {r:?}");
1367    }
1368
1369    #[test]
1370    fn walk_write_missing_intermediate_is_absence_no_autoviv() {
1371        let mut scope = Scope::new();
1372        scope.set("s", Value::Json(serde_json::json!({"web": {"port": 8080}})));
1373        let r = write_at(
1374            &mut scope,
1375            "s",
1376            vec![VarSegment::Key("api".into()), VarSegment::Key("port".into())],
1377        );
1378        assert!(matches!(r, Err(PathError::Absence(_))), "got: {r:?}");
1379        // The root is untouched — no partial autovivification.
1380        assert_eq!(
1381            scope.get("s"),
1382            Some(&Value::Json(serde_json::json!({"web": {"port": 8080}})))
1383        );
1384    }
1385
1386    #[test]
1387    fn walk_write_scalar_root_is_shape() {
1388        let mut scope = Scope::new();
1389        scope.set("y", Value::String("hi".into()));
1390        let r = write_at(&mut scope, "y", vec![VarSegment::Index(0)]);
1391        assert!(matches!(r, Err(PathError::Shape(_))), "got: {r:?}");
1392    }
1393
1394    #[test]
1395    fn walk_write_undefined_root_is_undefined_root() {
1396        let mut scope = Scope::new();
1397        let r = write_at(&mut scope, "z", vec![VarSegment::Index(0)]);
1398        assert!(matches!(r, Err(PathError::UndefinedRoot(_))), "got: {r:?}");
1399    }
1400
1401    #[test]
1402    fn walk_write_slice_lvalue_is_shape() {
1403        let mut scope = Scope::new();
1404        scope.set("xs", Value::Json(serde_json::json!([1, 2, 3])));
1405        let r = write_at(&mut scope, "xs", vec![VarSegment::Slice(Some(0), Some(2))]);
1406        assert!(matches!(r, Err(PathError::Shape(_))), "got: {r:?}");
1407    }
1408
1409    // ── walk_append (push) ──────────────────────────────────────────────────
1410
1411    #[test]
1412    fn walk_append_extends_a_list_in_place() {
1413        let mut scope = Scope::new();
1414        scope.set("xs", Value::Json(serde_json::json!(["a", "b"])));
1415        scope
1416            .walk_append(&VarPath::simple("xs"), vec![Value::String("c".into())])
1417            .expect("push should succeed");
1418        assert_eq!(scope.get("xs"), Some(&Value::Json(serde_json::json!(["a", "b", "c"]))));
1419    }
1420
1421    #[test]
1422    fn walk_append_undefined_target_is_a_loud_error() {
1423        let mut scope = Scope::new();
1424        let r = scope.walk_append(&VarPath::simple("nope"), vec![Value::Int(1)]);
1425        assert!(r.is_err(), "expected a loud error for an undefined target");
1426    }
1427
1428    #[test]
1429    fn walk_append_non_list_target_is_a_loud_error() {
1430        let mut scope = Scope::new();
1431        scope.set("y", Value::String("hi".into()));
1432        let r = scope.walk_append(&VarPath::simple("y"), vec![Value::Int(1)]);
1433        assert!(r.is_err(), "expected a loud error for a non-list target");
1434    }
1435
1436    #[test]
1437    fn walk_append_bracket_path_extends_a_nested_list_in_place() {
1438        let mut scope = Scope::new();
1439        scope.set(
1440            "services",
1441            Value::Json(serde_json::json!({"web": {"tags": ["a"]}})),
1442        );
1443        let path = VarPath {
1444            segments: vec![
1445                VarSegment::Field("services".into()),
1446                VarSegment::Key("web".into()),
1447                VarSegment::Key("tags".into()),
1448            ],
1449        };
1450        scope
1451            .walk_append(&path, vec![Value::String("b".into())])
1452            .expect("bracket-path push should succeed");
1453        assert_eq!(
1454            scope.get("services"),
1455            Some(&Value::Json(serde_json::json!({"web": {"tags": ["a", "b"]}})))
1456        );
1457    }
1458
1459    #[test]
1460    fn walk_append_bracket_path_missing_intermediate_is_a_loud_error() {
1461        let mut scope = Scope::new();
1462        scope.set("services", Value::Json(serde_json::json!({})));
1463        let path = VarPath {
1464            segments: vec![
1465                VarSegment::Field("services".into()),
1466                VarSegment::Key("web".into()),
1467                VarSegment::Key("tags".into()),
1468            ],
1469        };
1470        let r = scope.walk_append(&path, vec![Value::String("x".into())]);
1471        assert!(r.is_err(), "expected a loud error for a missing intermediate");
1472    }
1473
1474    #[test]
1475    fn walk_append_bracket_path_non_list_leaf_is_a_loud_error() {
1476        let mut scope = Scope::new();
1477        scope.set(
1478            "services",
1479            Value::Json(serde_json::json!({"web": {"port": 8080}})),
1480        );
1481        let path = VarPath {
1482            segments: vec![
1483                VarSegment::Field("services".into()),
1484                VarSegment::Key("web".into()),
1485                VarSegment::Key("port".into()),
1486            ],
1487        };
1488        let r = scope.walk_append(&path, vec![Value::Int(1)]);
1489        assert!(r.is_err(), "expected a loud error for a non-list leaf");
1490    }
1491}