1use 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#[derive(Debug, Clone, PartialEq)]
39pub enum PathError {
40 UndefinedRoot(String),
42 Absence(String),
44 Shape(String),
46}
47
48fn 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
63fn 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#[derive(Debug, Clone, PartialEq)]
80enum Step {
81 Index(usize),
83 Key(String),
85 Slice(usize, usize),
87}
88
89fn 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
114fn 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
127fn classify_slice(
131 json: &serde_json::Value,
132 start: Option<i64>,
133 end: Option<i64>,
134 path: &str,
135) -> Result<Step, PathError> {
136 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
162fn 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
171fn 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
188fn resolve_step(
194 container: &serde_json::Value,
195 seg: &VarSegment,
196 scope: &Scope,
197 path: &str,
198) -> Result<Step, PathError> {
199 if let VarSegment::Field(name) = seg {
203 return Err(dotted_access_error(path, name));
204 }
205
206 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 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 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
260fn 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 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
308fn 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
346fn 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
379fn 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#[derive(Debug, Clone)]
406pub struct Scope {
407 frames: Arc<Vec<HashMap<String, Value>>>,
410 exported: HashSet<String>,
412 last_result: Box<ExecResult>,
420 script_name: String,
422 positional: Vec<String>,
424 error_exit: bool,
426 errexit_suppressed: usize,
429 show_ast: bool,
431 trash_enabled: bool,
433 trash_max_size: u64,
436 glob_enabled: bool,
438 pid: u64,
444}
445
446impl Scope {
447 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, glob_enabled: true,
464 pid: 0,
465 }
466 }
467
468 pub fn pid(&self) -> u64 {
470 self.pid
471 }
472
473 pub fn set_pid(&mut self, pid: u64) {
477 self.pid = pid;
478 }
479
480 pub fn push_frame(&mut self) {
482 Arc::make_mut(&mut self.frames).push(HashMap::new());
483 }
484
485 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 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 pub fn set_global(&mut self, name: impl Into<String>, value: Value) {
511 let name = name.into();
512
513 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 if let Some(frame) = frames.first_mut() {
524 frame.insert(name, value);
525 }
526 }
527
528 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 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 pub fn set_last_result(&mut self, result: ExecResult) {
552 *self.last_result = result;
554 }
555
556 pub fn last_result(&self) -> &ExecResult {
558 &self.last_result
559 }
560
561 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 pub fn save_positional(&self) -> (String, Vec<String>) {
573 (self.script_name.clone(), self.positional.clone())
574 }
575
576 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 pub fn all_args(&self) -> &[String] {
593 &self.positional
594 }
595
596 pub fn arg_count(&self) -> usize {
598 self.positional.len()
599 }
600
601 pub fn error_exit_enabled(&self) -> bool {
606 self.error_exit && self.errexit_suppressed == 0
607 }
608
609 pub fn set_error_exit(&mut self, enabled: bool) {
611 self.error_exit = enabled;
612 }
613
614 pub fn suppress_errexit(&mut self) {
616 self.errexit_suppressed += 1;
617 }
618
619 pub fn unsuppress_errexit(&mut self) {
621 self.errexit_suppressed = self.errexit_suppressed.saturating_sub(1);
622 }
623
624 pub fn show_ast(&self) -> bool {
626 self.show_ast
627 }
628
629 pub fn set_show_ast(&mut self, enabled: bool) {
631 self.show_ast = enabled;
632 }
633
634 pub fn trash_enabled(&self) -> bool {
636 self.trash_enabled
637 }
638
639 pub fn set_trash_enabled(&mut self, enabled: bool) {
641 self.trash_enabled = enabled;
642 }
643
644 pub fn trash_max_size(&self) -> u64 {
646 self.trash_max_size
647 }
648
649 pub fn set_trash_max_size(&mut self, size: u64) {
651 self.trash_max_size = size;
652 }
653
654 pub fn glob_enabled(&self) -> bool {
656 self.glob_enabled
657 }
658
659 pub fn set_glob_enabled(&mut self, enabled: bool) {
661 self.glob_enabled = enabled;
662 }
663
664 pub fn export(&mut self, name: impl Into<String>) {
668 self.exported.insert(name.into());
669 }
670
671 pub fn is_exported(&self, name: &str) -> bool {
673 self.exported.contains(name)
674 }
675
676 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 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 pub fn unexport(&mut self, name: &str) {
701 self.exported.remove(name);
702 }
703
704 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 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 pub fn resolve_path(&self, path: &VarPath) -> Result<Value, PathError> {
742 let Some(VarSegment::Field(root_name)) = path.segments.first() else {
743 return Err(PathError::UndefinedRoot(String::new()));
745 };
746
747 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 let subscripts = &path.segments[1..];
765 if subscripts.is_empty() {
766 return Ok(root.clone());
767 }
768
769 if let Some(VarSegment::Field(name)) = subscripts.first() {
774 return Err(dotted_access_error(root_name, name));
775 }
776
777 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 let mut current = Cow::Borrowed(root_json);
803 let mut prefix = root_name.clone();
804 for seg in subscripts {
805 let step = resolve_step(¤t, 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 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 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 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(¤t)));
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 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 pub fn contains(&self, name: &str) -> bool {
945 self.get(name).is_some()
946 }
947
948 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 pub fn all(&self) -> Vec<(String, Value)> {
964 let mut result = std::collections::HashMap::new();
965 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 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 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 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 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 assert_eq!(scope.get_positional(0), Some("my_tool"));
1201 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 assert_eq!(scope.get_positional(4), None);
1207 }
1208
1209 #[test]
1210 fn positional_params_empty() {
1211 let scope = Scope::new();
1212 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 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)); scope.export("D"); 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 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 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 #[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}