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 arr = match json {
137 serde_json::Value::Array(a) => a,
138 serde_json::Value::Object(_) => {
139 return Err(PathError::Shape(format!(
140 "${{{path}[..]}}: cannot slice a record"
141 )))
142 }
143 _ => unreachable!("resolve_step guards non-collection containers"),
144 };
145 let len = arr.len() as i64;
146 let norm = |b: i64| -> i64 {
147 let b = if b < 0 { len + b } else { b };
148 b.clamp(0, len)
149 };
150 let s = start.map(norm).unwrap_or(0);
151 let e = end.map(norm).unwrap_or(len);
152 let (s, e) = if s >= e {
153 (s as usize, s as usize)
154 } else {
155 (s as usize, e as usize)
156 };
157 Ok(Step::Slice(s, e))
158}
159
160fn dotted_access_error(path: &str, field: &str) -> PathError {
164 PathError::Shape(format!(
165 "${{{path}…}}: kaish uses bracket access, not dots — write the key as a subscript: [{field}]"
166 ))
167}
168
169fn render_segment(seg: &VarSegment) -> String {
173 match seg {
174 VarSegment::Index(i) => format!("[{i}]"),
175 VarSegment::Key(k) => format!("[{k}]"),
176 VarSegment::Dynamic(v) => format!("[${v}]"),
177 VarSegment::Slice(a, b) => format!(
178 "[{}:{}]",
179 a.map(|n| n.to_string()).unwrap_or_default(),
180 b.map(|n| n.to_string()).unwrap_or_default()
181 ),
182 VarSegment::Field(f) => format!(".{f}"),
183 }
184}
185
186fn resolve_step(
192 container: &serde_json::Value,
193 seg: &VarSegment,
194 scope: &Scope,
195 path: &str,
196) -> Result<Step, PathError> {
197 if let VarSegment::Field(name) = seg {
201 return Err(dotted_access_error(path, name));
202 }
203
204 if !matches!(
206 container,
207 serde_json::Value::Array(_) | serde_json::Value::Object(_)
208 ) {
209 return Err(PathError::Shape(format!(
210 "${{{path}…}}: cannot subscript {} — it is not a collection",
211 type_name(&json_to_value_no_envelope(container.clone()))
212 )));
213 }
214
215 match seg {
216 VarSegment::Index(i) => classify_index(container, *i, path),
217 VarSegment::Key(k) => classify_key(container, k, path),
218 VarSegment::Slice(start, end) => classify_slice(container, *start, *end, path),
219 VarSegment::Dynamic(var) => {
220 let key_val = scope.get(var).ok_or_else(|| {
224 PathError::UndefinedRoot(format!("${{{path}[${var}]}}: ${var} is not set"))
225 })?;
226 match container {
227 serde_json::Value::Array(_) => {
228 let idx = value_as_index(key_val).ok_or_else(|| {
229 PathError::Shape(format!(
230 "${{{path}[${var}]}}: a list index must be an integer, got \"{}\"",
231 value_to_string(key_val)
232 ))
233 })?;
234 classify_index(container, idx, path)
235 }
236 serde_json::Value::Object(_) => Ok(Step::Key(value_to_string(key_val))),
237 _ => unreachable!("non-collection container guarded above"),
238 }
239 }
240 VarSegment::Field(_) => unreachable!("dotted segment handled above"),
241 }
242}
243
244fn descend<'a>(
250 current: Cow<'a, serde_json::Value>,
251 step: Step,
252 path: &str,
253) -> Result<Cow<'a, serde_json::Value>, PathError> {
254 match step {
255 Step::Slice(s, e) => {
256 let Some(arr) = current.as_array() else {
257 unreachable!("slice classified against an array")
258 };
259 Ok(Cow::Owned(serde_json::Value::Array(arr[s..e].to_vec())))
260 }
261 Step::Index(i) => match current {
262 Cow::Borrowed(j) => {
263 let Some(arr) = j.as_array() else {
264 unreachable!("index classified against an array")
265 };
266 Ok(Cow::Borrowed(&arr[i]))
267 }
268 Cow::Owned(j) => {
269 let Some(arr) = j.as_array() else {
270 unreachable!("index classified against an array")
271 };
272 Ok(Cow::Owned(arr[i].clone()))
273 }
274 },
275 Step::Key(k) => match current {
276 Cow::Borrowed(j) => match j.as_object().and_then(|m| m.get(&k)) {
277 Some(child) => Ok(Cow::Borrowed(child)),
278 None => Err(PathError::Absence(format!("${{{path}[{k}]}}: no such key"))),
279 },
280 Cow::Owned(j) => match j.as_object().and_then(|m| m.get(&k)) {
281 Some(child) => Ok(Cow::Owned(child.clone())),
282 None => Err(PathError::Absence(format!("${{{path}[{k}]}}: no such key"))),
283 },
284 },
285 }
286}
287
288fn descend_mut<'a>(
298 current: &'a mut serde_json::Value,
299 step: Step,
300 path: &str,
301) -> Result<&'a mut serde_json::Value, PathError> {
302 match step {
303 Step::Slice(..) => Err(PathError::Shape(format!(
304 "${{{path}[..]}}: slice lvalues are not supported — index or key paths only"
305 ))),
306 Step::Index(i) => {
307 let Some(arr) = current.as_array_mut() else {
308 unreachable!("index classified against an array")
309 };
310 Ok(&mut arr[i])
311 }
312 Step::Key(k) => {
313 let Some(map) = current.as_object_mut() else {
314 unreachable!("key classified against an object")
315 };
316 match map.get_mut(&k) {
317 Some(child) => Ok(child),
318 None => Err(PathError::Absence(format!(
319 "${{{path}[{k}]}}: no such key — no autovivification, create it first (e.g. `{path}[{k}]={{}}`)"
320 ))),
321 }
322 }
323 }
324}
325
326fn apply_leaf_write(
333 current: &mut serde_json::Value,
334 step: Step,
335 value: serde_json::Value,
336 path: &str,
337) -> Result<(), PathError> {
338 match step {
339 Step::Slice(..) => Err(PathError::Shape(format!(
340 "${{{path}[..]}}: slice lvalues are not supported — index or key paths only"
341 ))),
342 Step::Index(i) => {
343 let Some(arr) = current.as_array_mut() else {
344 unreachable!("index classified against an array")
345 };
346 arr[i] = value;
347 Ok(())
348 }
349 Step::Key(k) => {
350 let Some(map) = current.as_object_mut() else {
351 unreachable!("key classified against an object")
352 };
353 map.insert(k, value);
354 Ok(())
355 }
356 }
357}
358
359#[derive(Debug, Clone)]
370pub struct Scope {
371 frames: Arc<Vec<HashMap<String, Value>>>,
374 exported: HashSet<String>,
376 last_result: Box<ExecResult>,
384 script_name: String,
386 positional: Vec<String>,
388 error_exit: bool,
390 errexit_suppressed: usize,
393 show_ast: bool,
395 latch_enabled: bool,
397 trash_enabled: bool,
399 trash_max_size: u64,
402 glob_enabled: bool,
404 pid: u64,
410}
411
412impl Scope {
413 pub fn new() -> Self {
418 Self {
419 frames: Arc::new(vec![HashMap::new()]),
420 exported: HashSet::new(),
421 last_result: Box::new(ExecResult::default()),
422 script_name: String::new(),
423 positional: Vec::new(),
424 error_exit: false,
425 errexit_suppressed: 0,
426 show_ast: false,
427 latch_enabled: false,
428 trash_enabled: false,
429 trash_max_size: 10 * 1024 * 1024, glob_enabled: true,
431 pid: 0,
432 }
433 }
434
435 pub fn pid(&self) -> u64 {
437 self.pid
438 }
439
440 pub fn set_pid(&mut self, pid: u64) {
444 self.pid = pid;
445 }
446
447 pub fn push_frame(&mut self) {
449 Arc::make_mut(&mut self.frames).push(HashMap::new());
450 }
451
452 pub fn pop_frame(&mut self) {
456 if self.frames.len() > 1 {
457 Arc::make_mut(&mut self.frames).pop();
458 } else {
459 panic!("cannot pop the root scope frame");
460 }
461 }
462
463 pub fn set(&mut self, name: impl Into<String>, value: Value) {
467 if let Some(frame) = Arc::make_mut(&mut self.frames).last_mut() {
468 frame.insert(name.into(), value);
469 }
470 }
471
472 pub fn set_global(&mut self, name: impl Into<String>, value: Value) {
478 let name = name.into();
479
480 let frames = Arc::make_mut(&mut self.frames);
482 for frame in frames.iter_mut().rev() {
483 if let std::collections::hash_map::Entry::Occupied(mut e) = frame.entry(name.clone()) {
484 e.insert(value);
485 return;
486 }
487 }
488
489 if let Some(frame) = frames.first_mut() {
491 frame.insert(name, value);
492 }
493 }
494
495 pub fn get(&self, name: &str) -> Option<&Value> {
497 for frame in self.frames.iter().rev() {
498 if let Some(value) = frame.get(name) {
499 return Some(value);
500 }
501 }
502 None
503 }
504
505 pub fn remove(&mut self, name: &str) -> Option<Value> {
509 for frame in Arc::make_mut(&mut self.frames).iter_mut().rev() {
510 if let Some(value) = frame.remove(name) {
511 return Some(value);
512 }
513 }
514 None
515 }
516
517 pub fn set_last_result(&mut self, result: ExecResult) {
519 *self.last_result = result;
521 }
522
523 pub fn last_result(&self) -> &ExecResult {
525 &self.last_result
526 }
527
528 pub fn set_positional(&mut self, script_name: impl Into<String>, args: Vec<String>) {
532 self.script_name = script_name.into();
533 self.positional = args;
534 }
535
536 pub fn save_positional(&self) -> (String, Vec<String>) {
540 (self.script_name.clone(), self.positional.clone())
541 }
542
543 pub fn get_positional(&self, n: usize) -> Option<&str> {
547 if n == 0 {
548 if self.script_name.is_empty() {
549 None
550 } else {
551 Some(&self.script_name)
552 }
553 } else {
554 self.positional.get(n - 1).map(|s| s.as_str())
555 }
556 }
557
558 pub fn all_args(&self) -> &[String] {
560 &self.positional
561 }
562
563 pub fn arg_count(&self) -> usize {
565 self.positional.len()
566 }
567
568 pub fn error_exit_enabled(&self) -> bool {
573 self.error_exit && self.errexit_suppressed == 0
574 }
575
576 pub fn set_error_exit(&mut self, enabled: bool) {
578 self.error_exit = enabled;
579 }
580
581 pub fn suppress_errexit(&mut self) {
583 self.errexit_suppressed += 1;
584 }
585
586 pub fn unsuppress_errexit(&mut self) {
588 self.errexit_suppressed = self.errexit_suppressed.saturating_sub(1);
589 }
590
591 pub fn show_ast(&self) -> bool {
593 self.show_ast
594 }
595
596 pub fn set_show_ast(&mut self, enabled: bool) {
598 self.show_ast = enabled;
599 }
600
601 pub fn latch_enabled(&self) -> bool {
603 self.latch_enabled
604 }
605
606 pub fn set_latch_enabled(&mut self, enabled: bool) {
608 self.latch_enabled = enabled;
609 }
610
611 pub fn trash_enabled(&self) -> bool {
613 self.trash_enabled
614 }
615
616 pub fn set_trash_enabled(&mut self, enabled: bool) {
618 self.trash_enabled = enabled;
619 }
620
621 pub fn trash_max_size(&self) -> u64 {
623 self.trash_max_size
624 }
625
626 pub fn set_trash_max_size(&mut self, size: u64) {
628 self.trash_max_size = size;
629 }
630
631 pub fn glob_enabled(&self) -> bool {
633 self.glob_enabled
634 }
635
636 pub fn set_glob_enabled(&mut self, enabled: bool) {
638 self.glob_enabled = enabled;
639 }
640
641 pub fn export(&mut self, name: impl Into<String>) {
645 self.exported.insert(name.into());
646 }
647
648 pub fn is_exported(&self, name: &str) -> bool {
650 self.exported.contains(name)
651 }
652
653 pub fn set_exported(&mut self, name: impl Into<String>, value: Value) {
660 let name = name.into();
661 self.set(&name, value);
662 self.export(name);
663 }
664
665 pub fn set_exported_global(&mut self, name: impl Into<String>, value: Value) {
671 let name = name.into();
672 self.set_global(&name, value);
673 self.export(name);
674 }
675
676 pub fn unexport(&mut self, name: &str) {
678 self.exported.remove(name);
679 }
680
681 pub fn exported_vars(&self) -> Vec<(String, Value)> {
685 let mut result = Vec::new();
686 for name in &self.exported {
687 if let Some(value) = self.get(name) {
688 result.push((name.clone(), value.clone()));
689 }
690 }
691 result.sort_by(|(a, _), (b, _)| a.cmp(b));
692 result
693 }
694
695 pub fn exported_names(&self) -> Vec<&str> {
697 let mut names: Vec<&str> = self.exported.iter().map(|s| s.as_str()).collect();
698 names.sort();
699 names
700 }
701
702 pub fn resolve_path(&self, path: &VarPath) -> Result<Value, PathError> {
719 let Some(VarSegment::Field(root_name)) = path.segments.first() else {
720 return Err(PathError::UndefinedRoot(String::new()));
722 };
723
724 if root_name == "?" {
726 if path.segments.len() == 1 {
727 return Ok(Value::Int(self.last_result.code));
728 }
729 return Err(PathError::Shape(
730 "$? is the POSIX exit code, not a collection — use `kaish-last` for structured data"
731 .to_string(),
732 ));
733 }
734
735 let root = self
736 .get(root_name)
737 .ok_or_else(|| PathError::UndefinedRoot(root_name.clone()))?;
738
739 let subscripts = &path.segments[1..];
742 if subscripts.is_empty() {
743 return Ok(root.clone());
744 }
745
746 if let Some(VarSegment::Field(name)) = subscripts.first() {
751 return Err(dotted_access_error(root_name, name));
752 }
753
754 let root_json = match root {
758 Value::Json(j) => j,
759 other => {
760 return Err(PathError::Shape(format!(
761 "${{{root_name}…}}: cannot subscript {} — it is not a collection",
762 type_name(other)
763 )))
764 }
765 };
766
767 let mut current = Cow::Borrowed(root_json);
772 let mut prefix = root_name.clone();
773 for seg in subscripts {
774 let step = resolve_step(¤t, seg, self, &prefix)?;
775 current = descend(current, step, &prefix)?;
776 prefix.push_str(&render_segment(seg));
777 }
778 Ok(json_to_value_no_envelope(current.into_owned()))
779 }
780
781 pub fn walk_write(&mut self, path: &VarPath, value: Value) -> Result<(), PathError> {
800 let Some(VarSegment::Field(root_name)) = path.segments.first() else {
801 return Err(PathError::UndefinedRoot(String::new()));
802 };
803
804 let root = self
805 .get(root_name)
806 .ok_or_else(|| PathError::UndefinedRoot(root_name.clone()))?;
807
808 let mut root_json = match root {
809 Value::Json(j) => j.clone(),
810 other => {
811 return Err(PathError::Shape(format!(
812 "${{{root_name}…}}: cannot subscript {} — it is not a collection",
813 type_name(other)
814 )))
815 }
816 };
817
818 let subscripts = &path.segments[1..];
819 let Some((last, intermediates)) = subscripts.split_last() else {
820 return Err(PathError::Shape(format!(
824 "{root_name}: assignment target has no subscript"
825 )));
826 };
827
828 let mut current = &mut root_json;
829 let mut prefix = root_name.clone();
830 for seg in intermediates {
831 let step = resolve_step(current, seg, self, &prefix)?;
832 current = descend_mut(current, step, &prefix)?;
833 prefix.push_str(&render_segment(seg));
834 }
835
836 let step = resolve_step(current, last, self, &prefix)?;
837 apply_leaf_write(current, step, value_to_json(&value), &prefix)?;
838
839 self.set_global(root_name.clone(), Value::Json(root_json));
840 Ok(())
841 }
842
843 pub fn walk_append(&mut self, name: &str, values: Vec<Value>) -> Result<(), String> {
851 let current = self
852 .get(name)
853 .ok_or_else(|| format!("push: {name} is not defined"))?;
854 if !matches!(current, Value::Json(serde_json::Value::Array(_))) {
855 return Err(format!("push: {name} is not a list ({})", type_name(current)));
856 }
857 let Value::Json(serde_json::Value::Array(mut arr)) = current.clone() else {
858 unreachable!("checked above")
859 };
860 arr.extend(values.iter().map(value_to_json));
861 self.set_global(name, Value::Json(serde_json::Value::Array(arr)));
862 Ok(())
863 }
864
865 pub fn contains(&self, name: &str) -> bool {
867 self.get(name).is_some()
868 }
869
870 pub fn all_names(&self) -> Vec<&str> {
872 let mut names: Vec<&str> = self
873 .frames
874 .iter()
875 .flat_map(|f| f.keys().map(|s| s.as_str()))
876 .collect();
877 names.sort();
878 names.dedup();
879 names
880 }
881
882 pub fn all(&self) -> Vec<(String, Value)> {
886 let mut result = std::collections::HashMap::new();
887 for frame in self.frames.iter() {
889 for (name, value) in frame {
890 result.insert(name.clone(), value.clone());
891 }
892 }
893 let mut pairs: Vec<_> = result.into_iter().collect();
894 pairs.sort_by(|(a, _), (b, _)| a.cmp(b));
895 pairs
896 }
897}
898
899impl Default for Scope {
900 fn default() -> Self {
901 Self::new()
902 }
903}
904
905#[cfg(test)]
906mod tests {
907 use super::*;
908
909 #[test]
910 fn new_scope_has_one_frame() {
911 let scope = Scope::new();
912 assert_eq!(scope.frames.len(), 1);
913 }
914
915 #[test]
916 fn set_and_get_variable() {
917 let mut scope = Scope::new();
918 scope.set("X", Value::Int(42));
919 assert_eq!(scope.get("X"), Some(&Value::Int(42)));
920 }
921
922 #[test]
923 fn get_nonexistent_returns_none() {
924 let scope = Scope::new();
925 assert_eq!(scope.get("MISSING"), None);
926 }
927
928 #[test]
929 fn inner_frame_shadows_outer() {
930 let mut scope = Scope::new();
931 scope.set("X", Value::Int(1));
932 scope.push_frame();
933 scope.set("X", Value::Int(2));
934 assert_eq!(scope.get("X"), Some(&Value::Int(2)));
935 scope.pop_frame();
936 assert_eq!(scope.get("X"), Some(&Value::Int(1)));
937 }
938
939 #[test]
940 fn inner_frame_can_see_outer_vars() {
941 let mut scope = Scope::new();
942 scope.set("OUTER", Value::String("visible".into()));
943 scope.push_frame();
944 assert_eq!(scope.get("OUTER"), Some(&Value::String("visible".into())));
945 }
946
947 #[test]
948 fn resolve_simple_path() {
949 let mut scope = Scope::new();
950 scope.set("NAME", Value::String("Alice".into()));
951
952 let path = VarPath::simple("NAME");
953 assert_eq!(
954 scope.resolve_path(&path),
955 Ok(Value::String("Alice".into()))
956 );
957 }
958
959 #[test]
960 fn resolve_bare_last_result_returns_exit_code() {
961 let mut scope = Scope::new();
962 scope.set_last_result(ExecResult::failure(127, "not found"));
963
964 let path = VarPath {
965 segments: vec![VarSegment::Field("?".into())],
966 };
967 assert_eq!(scope.resolve_path(&path), Ok(Value::Int(127)));
968 }
969
970 #[test]
971 fn resolve_last_result_field_access_is_rejected() {
972 let mut scope = Scope::new();
976 scope.set_last_result(ExecResult::success_with_data(
977 "1",
978 Value::Json(serde_json::json!({"count": 5})),
979 ));
980
981 let path = VarPath {
982 segments: vec![
983 VarSegment::Field("?".into()),
984 VarSegment::Field("data".into()),
985 ],
986 };
987 assert!(matches!(
988 scope.resolve_path(&path),
989 Err(PathError::Shape(_))
990 ));
991 }
992
993 #[test]
994 fn resolve_dotted_access_on_scalar_is_a_loud_error() {
995 let mut scope = Scope::new();
996 scope.set("X", Value::Int(42));
997
998 let path = VarPath {
1000 segments: vec![
1001 VarSegment::Field("X".into()),
1002 VarSegment::Field("invalid".into()),
1003 ],
1004 };
1005 assert!(matches!(
1006 scope.resolve_path(&path),
1007 Err(PathError::Shape(_))
1008 ));
1009 }
1010
1011 #[test]
1012 fn resolve_undefined_root_is_soft() {
1013 let scope = Scope::new();
1014 let path = VarPath::simple("NOPE");
1015 assert!(matches!(
1016 scope.resolve_path(&path),
1017 Err(PathError::UndefinedRoot(_))
1018 ));
1019 }
1020
1021 fn subscripted(scope: &mut Scope, root: &str, value: serde_json::Value, seg: VarSegment) -> Result<Value, PathError> {
1028 scope.set(root, Value::Json(value));
1029 let path = VarPath {
1030 segments: vec![VarSegment::Field(root.into()), seg],
1031 };
1032 scope.resolve_path(&path)
1033 }
1034
1035 #[test]
1036 fn out_of_bounds_index_is_absence() {
1037 let mut scope = Scope::new();
1038 let r = subscripted(&mut scope, "xs", serde_json::json!([1, 2]), VarSegment::Index(9));
1039 assert!(matches!(r, Err(PathError::Absence(_))), "got: {r:?}");
1040 }
1041
1042 #[test]
1043 fn missing_record_key_is_absence() {
1044 let mut scope = Scope::new();
1045 let r = subscripted(&mut scope, "u", serde_json::json!({"name": "amy"}), VarSegment::Key("nope".into()));
1046 assert!(matches!(r, Err(PathError::Absence(_))), "got: {r:?}");
1047 }
1048
1049 #[test]
1050 fn string_key_on_a_list_is_shape() {
1051 let mut scope = Scope::new();
1052 let r = subscripted(&mut scope, "xs", serde_json::json!([1, 2]), VarSegment::Key("web".into()));
1053 assert!(matches!(r, Err(PathError::Shape(_))), "got: {r:?}");
1054 }
1055
1056 #[test]
1057 fn integer_index_on_a_record_is_shape() {
1058 let mut scope = Scope::new();
1059 let r = subscripted(&mut scope, "u", serde_json::json!({"name": "amy"}), VarSegment::Index(0));
1060 assert!(matches!(r, Err(PathError::Shape(_))), "got: {r:?}");
1061 }
1062
1063 #[test]
1064 fn subscripting_a_scalar_is_shape() {
1065 let mut scope = Scope::new();
1066 scope.set("s", Value::String("hello".into()));
1067 let path = VarPath {
1068 segments: vec![VarSegment::Field("s".into()), VarSegment::Index(0)],
1069 };
1070 assert!(matches!(scope.resolve_path(&path), Err(PathError::Shape(_))));
1071 }
1072
1073 #[test]
1074 fn unset_dynamic_key_is_undefined_root_not_absence() {
1075 let mut scope = Scope::new();
1078 let r = subscripted(
1079 &mut scope,
1080 "r",
1081 serde_json::json!({"name": "amy"}),
1082 VarSegment::Dynamic("k".into()),
1083 );
1084 assert!(matches!(r, Err(PathError::UndefinedRoot(_))), "got: {r:?}");
1085 }
1086
1087 #[test]
1088 fn contains_finds_variable() {
1089 let mut scope = Scope::new();
1090 scope.set("EXISTS", Value::Bool(true));
1091 assert!(scope.contains("EXISTS"));
1092 assert!(!scope.contains("MISSING"));
1093 }
1094
1095 #[test]
1096 fn all_names_lists_variables() {
1097 let mut scope = Scope::new();
1098 scope.set("A", Value::Int(1));
1099 scope.set("B", Value::Int(2));
1100 scope.push_frame();
1101 scope.set("C", Value::Int(3));
1102
1103 let names = scope.all_names();
1104 assert!(names.contains(&"A"));
1105 assert!(names.contains(&"B"));
1106 assert!(names.contains(&"C"));
1107 }
1108
1109 #[test]
1110 #[should_panic(expected = "cannot pop the root scope frame")]
1111 fn pop_root_frame_panics() {
1112 let mut scope = Scope::new();
1113 scope.pop_frame();
1114 }
1115
1116 #[test]
1117 fn positional_params_basic() {
1118 let mut scope = Scope::new();
1119 scope.set_positional("my_tool", vec!["arg1".into(), "arg2".into(), "arg3".into()]);
1120
1121 assert_eq!(scope.get_positional(0), Some("my_tool"));
1123 assert_eq!(scope.get_positional(1), Some("arg1"));
1125 assert_eq!(scope.get_positional(2), Some("arg2"));
1126 assert_eq!(scope.get_positional(3), Some("arg3"));
1127 assert_eq!(scope.get_positional(4), None);
1129 }
1130
1131 #[test]
1132 fn positional_params_empty() {
1133 let scope = Scope::new();
1134 assert_eq!(scope.get_positional(0), None);
1136 assert_eq!(scope.get_positional(1), None);
1137 assert_eq!(scope.arg_count(), 0);
1138 assert!(scope.all_args().is_empty());
1139 }
1140
1141 #[test]
1142 fn all_args_returns_slice() {
1143 let mut scope = Scope::new();
1144 scope.set_positional("test", vec!["a".into(), "b".into(), "c".into()]);
1145
1146 let args = scope.all_args();
1147 assert_eq!(args, &["a", "b", "c"]);
1148 }
1149
1150 #[test]
1151 fn arg_count_returns_count() {
1152 let mut scope = Scope::new();
1153 scope.set_positional("test", vec!["one".into(), "two".into()]);
1154
1155 assert_eq!(scope.arg_count(), 2);
1156 }
1157
1158 #[test]
1159 fn export_marks_variable() {
1160 let mut scope = Scope::new();
1161 scope.set("X", Value::Int(42));
1162
1163 assert!(!scope.is_exported("X"));
1164 scope.export("X");
1165 assert!(scope.is_exported("X"));
1166 }
1167
1168 #[test]
1169 fn set_exported_sets_and_exports() {
1170 let mut scope = Scope::new();
1171 scope.set_exported("PATH", Value::String("/usr/bin".into()));
1172
1173 assert!(scope.is_exported("PATH"));
1174 assert_eq!(scope.get("PATH"), Some(&Value::String("/usr/bin".into())));
1175 }
1176
1177 #[test]
1178 fn unexport_removes_export_marker() {
1179 let mut scope = Scope::new();
1180 scope.set_exported("VAR", Value::Int(1));
1181 assert!(scope.is_exported("VAR"));
1182
1183 scope.unexport("VAR");
1184 assert!(!scope.is_exported("VAR"));
1185 assert!(scope.get("VAR").is_some());
1187 }
1188
1189 #[test]
1190 fn exported_vars_returns_only_exported_with_values() {
1191 let mut scope = Scope::new();
1192 scope.set_exported("A", Value::Int(1));
1193 scope.set_exported("B", Value::Int(2));
1194 scope.set("C", Value::Int(3)); scope.export("D"); let exported = scope.exported_vars();
1198 assert_eq!(exported.len(), 2);
1199 assert_eq!(exported[0], ("A".to_string(), Value::Int(1)));
1200 assert_eq!(exported[1], ("B".to_string(), Value::Int(2)));
1201 }
1202
1203 #[test]
1204 fn exported_names_returns_sorted_names() {
1205 let mut scope = Scope::new();
1206 scope.export("Z");
1207 scope.export("A");
1208 scope.export("M");
1209
1210 let names = scope.exported_names();
1211 assert_eq!(names, vec!["A", "M", "Z"]);
1212 }
1213
1214 fn write_at(
1218 scope: &mut Scope,
1219 root: &str,
1220 segs: Vec<VarSegment>,
1221 ) -> Result<(), PathError> {
1222 let mut segments = vec![VarSegment::Field(root.into())];
1223 segments.extend(segs);
1224 scope.walk_write(&VarPath { segments }, Value::Int(0))
1225 }
1226
1227 #[test]
1228 fn walk_write_list_index_update() {
1229 let mut scope = Scope::new();
1230 scope.set("xs", Value::Json(serde_json::json!([1, 2, 3])));
1231 let path = VarPath {
1232 segments: vec![VarSegment::Field("xs".into()), VarSegment::Index(0)],
1233 };
1234 scope.walk_write(&path, Value::Int(9)).expect("write should succeed");
1235 assert_eq!(scope.get("xs"), Some(&Value::Json(serde_json::json!([9, 2, 3]))));
1236 }
1237
1238 #[test]
1239 fn walk_write_negative_index() {
1240 let mut scope = Scope::new();
1241 scope.set("xs", Value::Json(serde_json::json!([1, 2, 3])));
1242 let path = VarPath {
1243 segments: vec![VarSegment::Field("xs".into()), VarSegment::Index(-1)],
1244 };
1245 scope.walk_write(&path, Value::Int(7)).expect("write should succeed");
1246 assert_eq!(scope.get("xs"), Some(&Value::Json(serde_json::json!([1, 2, 7]))));
1247 }
1248
1249 #[test]
1250 fn walk_write_inserts_a_new_record_key() {
1251 let mut scope = Scope::new();
1252 scope.set("u", Value::Json(serde_json::json!({"port": 8080})));
1253 let path = VarPath {
1254 segments: vec![VarSegment::Field("u".into()), VarSegment::Key("host".into())],
1255 };
1256 scope
1257 .walk_write(&path, Value::String("localhost".into()))
1258 .expect("write should succeed");
1259 assert_eq!(
1260 scope.get("u"),
1261 Some(&Value::Json(serde_json::json!({"port": 8080, "host": "localhost"})))
1262 );
1263 }
1264
1265 #[test]
1266 fn walk_write_deep_path_updates_nested_key() {
1267 let mut scope = Scope::new();
1268 scope.set("s", Value::Json(serde_json::json!({"web": {"port": 8080}})));
1269 let path = VarPath {
1270 segments: vec![
1271 VarSegment::Field("s".into()),
1272 VarSegment::Key("web".into()),
1273 VarSegment::Key("port".into()),
1274 ],
1275 };
1276 scope.walk_write(&path, Value::Int(9000)).expect("write should succeed");
1277 assert_eq!(
1278 scope.get("s"),
1279 Some(&Value::Json(serde_json::json!({"web": {"port": 9000}})))
1280 );
1281 }
1282
1283 #[test]
1284 fn walk_write_out_of_bounds_index_is_absence() {
1285 let mut scope = Scope::new();
1286 scope.set("xs", Value::Json(serde_json::json!([1, 2, 3])));
1287 let r = write_at(&mut scope, "xs", vec![VarSegment::Index(9)]);
1288 assert!(matches!(r, Err(PathError::Absence(_))), "got: {r:?}");
1289 }
1290
1291 #[test]
1292 fn walk_write_missing_intermediate_is_absence_no_autoviv() {
1293 let mut scope = Scope::new();
1294 scope.set("s", Value::Json(serde_json::json!({"web": {"port": 8080}})));
1295 let r = write_at(
1296 &mut scope,
1297 "s",
1298 vec![VarSegment::Key("api".into()), VarSegment::Key("port".into())],
1299 );
1300 assert!(matches!(r, Err(PathError::Absence(_))), "got: {r:?}");
1301 assert_eq!(
1303 scope.get("s"),
1304 Some(&Value::Json(serde_json::json!({"web": {"port": 8080}})))
1305 );
1306 }
1307
1308 #[test]
1309 fn walk_write_scalar_root_is_shape() {
1310 let mut scope = Scope::new();
1311 scope.set("y", Value::String("hi".into()));
1312 let r = write_at(&mut scope, "y", vec![VarSegment::Index(0)]);
1313 assert!(matches!(r, Err(PathError::Shape(_))), "got: {r:?}");
1314 }
1315
1316 #[test]
1317 fn walk_write_undefined_root_is_undefined_root() {
1318 let mut scope = Scope::new();
1319 let r = write_at(&mut scope, "z", vec![VarSegment::Index(0)]);
1320 assert!(matches!(r, Err(PathError::UndefinedRoot(_))), "got: {r:?}");
1321 }
1322
1323 #[test]
1324 fn walk_write_slice_lvalue_is_shape() {
1325 let mut scope = Scope::new();
1326 scope.set("xs", Value::Json(serde_json::json!([1, 2, 3])));
1327 let r = write_at(&mut scope, "xs", vec![VarSegment::Slice(Some(0), Some(2))]);
1328 assert!(matches!(r, Err(PathError::Shape(_))), "got: {r:?}");
1329 }
1330
1331 #[test]
1334 fn walk_append_extends_a_list_in_place() {
1335 let mut scope = Scope::new();
1336 scope.set("xs", Value::Json(serde_json::json!(["a", "b"])));
1337 scope
1338 .walk_append("xs", vec![Value::String("c".into())])
1339 .expect("push should succeed");
1340 assert_eq!(scope.get("xs"), Some(&Value::Json(serde_json::json!(["a", "b", "c"]))));
1341 }
1342
1343 #[test]
1344 fn walk_append_undefined_target_is_a_loud_error() {
1345 let mut scope = Scope::new();
1346 let r = scope.walk_append("nope", vec![Value::Int(1)]);
1347 assert!(r.is_err(), "expected a loud error for an undefined target");
1348 }
1349
1350 #[test]
1351 fn walk_append_non_list_target_is_a_loud_error() {
1352 let mut scope = Scope::new();
1353 scope.set("y", Value::String("hi".into()));
1354 let r = scope.walk_append("y", vec![Value::Int(1)]);
1355 assert!(r.is_err(), "expected a loud error for a non-list target");
1356 }
1357}