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: ExecResult,
378 script_name: String,
380 positional: Vec<String>,
382 error_exit: bool,
384 errexit_suppressed: usize,
387 show_ast: bool,
389 latch_enabled: bool,
391 trash_enabled: bool,
393 trash_max_size: u64,
396 glob_enabled: bool,
398 pid: u64,
404}
405
406impl Scope {
407 pub fn new() -> Self {
412 Self {
413 frames: Arc::new(vec![HashMap::new()]),
414 exported: HashSet::new(),
415 last_result: ExecResult::default(),
416 script_name: String::new(),
417 positional: Vec::new(),
418 error_exit: false,
419 errexit_suppressed: 0,
420 show_ast: false,
421 latch_enabled: false,
422 trash_enabled: false,
423 trash_max_size: 10 * 1024 * 1024, glob_enabled: true,
425 pid: 0,
426 }
427 }
428
429 pub fn pid(&self) -> u64 {
431 self.pid
432 }
433
434 pub fn set_pid(&mut self, pid: u64) {
438 self.pid = pid;
439 }
440
441 pub fn push_frame(&mut self) {
443 Arc::make_mut(&mut self.frames).push(HashMap::new());
444 }
445
446 pub fn pop_frame(&mut self) {
450 if self.frames.len() > 1 {
451 Arc::make_mut(&mut self.frames).pop();
452 } else {
453 panic!("cannot pop the root scope frame");
454 }
455 }
456
457 pub fn set(&mut self, name: impl Into<String>, value: Value) {
461 if let Some(frame) = Arc::make_mut(&mut self.frames).last_mut() {
462 frame.insert(name.into(), value);
463 }
464 }
465
466 pub fn set_global(&mut self, name: impl Into<String>, value: Value) {
472 let name = name.into();
473
474 let frames = Arc::make_mut(&mut self.frames);
476 for frame in frames.iter_mut().rev() {
477 if let std::collections::hash_map::Entry::Occupied(mut e) = frame.entry(name.clone()) {
478 e.insert(value);
479 return;
480 }
481 }
482
483 if let Some(frame) = frames.first_mut() {
485 frame.insert(name, value);
486 }
487 }
488
489 pub fn get(&self, name: &str) -> Option<&Value> {
491 for frame in self.frames.iter().rev() {
492 if let Some(value) = frame.get(name) {
493 return Some(value);
494 }
495 }
496 None
497 }
498
499 pub fn remove(&mut self, name: &str) -> Option<Value> {
503 for frame in Arc::make_mut(&mut self.frames).iter_mut().rev() {
504 if let Some(value) = frame.remove(name) {
505 return Some(value);
506 }
507 }
508 None
509 }
510
511 pub fn set_last_result(&mut self, result: ExecResult) {
513 self.last_result = result;
514 }
515
516 pub fn last_result(&self) -> &ExecResult {
518 &self.last_result
519 }
520
521 pub fn set_positional(&mut self, script_name: impl Into<String>, args: Vec<String>) {
525 self.script_name = script_name.into();
526 self.positional = args;
527 }
528
529 pub fn save_positional(&self) -> (String, Vec<String>) {
533 (self.script_name.clone(), self.positional.clone())
534 }
535
536 pub fn get_positional(&self, n: usize) -> Option<&str> {
540 if n == 0 {
541 if self.script_name.is_empty() {
542 None
543 } else {
544 Some(&self.script_name)
545 }
546 } else {
547 self.positional.get(n - 1).map(|s| s.as_str())
548 }
549 }
550
551 pub fn all_args(&self) -> &[String] {
553 &self.positional
554 }
555
556 pub fn arg_count(&self) -> usize {
558 self.positional.len()
559 }
560
561 pub fn error_exit_enabled(&self) -> bool {
566 self.error_exit && self.errexit_suppressed == 0
567 }
568
569 pub fn set_error_exit(&mut self, enabled: bool) {
571 self.error_exit = enabled;
572 }
573
574 pub fn suppress_errexit(&mut self) {
576 self.errexit_suppressed += 1;
577 }
578
579 pub fn unsuppress_errexit(&mut self) {
581 self.errexit_suppressed = self.errexit_suppressed.saturating_sub(1);
582 }
583
584 pub fn show_ast(&self) -> bool {
586 self.show_ast
587 }
588
589 pub fn set_show_ast(&mut self, enabled: bool) {
591 self.show_ast = enabled;
592 }
593
594 pub fn latch_enabled(&self) -> bool {
596 self.latch_enabled
597 }
598
599 pub fn set_latch_enabled(&mut self, enabled: bool) {
601 self.latch_enabled = enabled;
602 }
603
604 pub fn trash_enabled(&self) -> bool {
606 self.trash_enabled
607 }
608
609 pub fn set_trash_enabled(&mut self, enabled: bool) {
611 self.trash_enabled = enabled;
612 }
613
614 pub fn trash_max_size(&self) -> u64 {
616 self.trash_max_size
617 }
618
619 pub fn set_trash_max_size(&mut self, size: u64) {
621 self.trash_max_size = size;
622 }
623
624 pub fn glob_enabled(&self) -> bool {
626 self.glob_enabled
627 }
628
629 pub fn set_glob_enabled(&mut self, enabled: bool) {
631 self.glob_enabled = enabled;
632 }
633
634 pub fn export(&mut self, name: impl Into<String>) {
638 self.exported.insert(name.into());
639 }
640
641 pub fn is_exported(&self, name: &str) -> bool {
643 self.exported.contains(name)
644 }
645
646 pub fn set_exported(&mut self, name: impl Into<String>, value: Value) {
653 let name = name.into();
654 self.set(&name, value);
655 self.export(name);
656 }
657
658 pub fn set_exported_global(&mut self, name: impl Into<String>, value: Value) {
664 let name = name.into();
665 self.set_global(&name, value);
666 self.export(name);
667 }
668
669 pub fn unexport(&mut self, name: &str) {
671 self.exported.remove(name);
672 }
673
674 pub fn exported_vars(&self) -> Vec<(String, Value)> {
678 let mut result = Vec::new();
679 for name in &self.exported {
680 if let Some(value) = self.get(name) {
681 result.push((name.clone(), value.clone()));
682 }
683 }
684 result.sort_by(|(a, _), (b, _)| a.cmp(b));
685 result
686 }
687
688 pub fn exported_names(&self) -> Vec<&str> {
690 let mut names: Vec<&str> = self.exported.iter().map(|s| s.as_str()).collect();
691 names.sort();
692 names
693 }
694
695 pub fn resolve_path(&self, path: &VarPath) -> Result<Value, PathError> {
712 let Some(VarSegment::Field(root_name)) = path.segments.first() else {
713 return Err(PathError::UndefinedRoot(String::new()));
715 };
716
717 if root_name == "?" {
719 if path.segments.len() == 1 {
720 return Ok(Value::Int(self.last_result.code));
721 }
722 return Err(PathError::Shape(
723 "$? is the POSIX exit code, not a collection — use `kaish-last` for structured data"
724 .to_string(),
725 ));
726 }
727
728 let root = self
729 .get(root_name)
730 .ok_or_else(|| PathError::UndefinedRoot(root_name.clone()))?;
731
732 let subscripts = &path.segments[1..];
735 if subscripts.is_empty() {
736 return Ok(root.clone());
737 }
738
739 if let Some(VarSegment::Field(name)) = subscripts.first() {
744 return Err(dotted_access_error(root_name, name));
745 }
746
747 let root_json = match root {
751 Value::Json(j) => j,
752 other => {
753 return Err(PathError::Shape(format!(
754 "${{{root_name}…}}: cannot subscript {} — it is not a collection",
755 type_name(other)
756 )))
757 }
758 };
759
760 let mut current = Cow::Borrowed(root_json);
765 let mut prefix = root_name.clone();
766 for seg in subscripts {
767 let step = resolve_step(¤t, seg, self, &prefix)?;
768 current = descend(current, step, &prefix)?;
769 prefix.push_str(&render_segment(seg));
770 }
771 Ok(json_to_value_no_envelope(current.into_owned()))
772 }
773
774 pub fn walk_write(&mut self, path: &VarPath, value: Value) -> Result<(), PathError> {
793 let Some(VarSegment::Field(root_name)) = path.segments.first() else {
794 return Err(PathError::UndefinedRoot(String::new()));
795 };
796
797 let root = self
798 .get(root_name)
799 .ok_or_else(|| PathError::UndefinedRoot(root_name.clone()))?;
800
801 let mut root_json = match root {
802 Value::Json(j) => j.clone(),
803 other => {
804 return Err(PathError::Shape(format!(
805 "${{{root_name}…}}: cannot subscript {} — it is not a collection",
806 type_name(other)
807 )))
808 }
809 };
810
811 let subscripts = &path.segments[1..];
812 let Some((last, intermediates)) = subscripts.split_last() else {
813 return Err(PathError::Shape(format!(
817 "{root_name}: assignment target has no subscript"
818 )));
819 };
820
821 let mut current = &mut root_json;
822 let mut prefix = root_name.clone();
823 for seg in intermediates {
824 let step = resolve_step(current, seg, self, &prefix)?;
825 current = descend_mut(current, step, &prefix)?;
826 prefix.push_str(&render_segment(seg));
827 }
828
829 let step = resolve_step(current, last, self, &prefix)?;
830 apply_leaf_write(current, step, value_to_json(&value), &prefix)?;
831
832 self.set_global(root_name.clone(), Value::Json(root_json));
833 Ok(())
834 }
835
836 pub fn walk_append(&mut self, name: &str, values: Vec<Value>) -> Result<(), String> {
844 let current = self
845 .get(name)
846 .ok_or_else(|| format!("push: {name} is not defined"))?;
847 if !matches!(current, Value::Json(serde_json::Value::Array(_))) {
848 return Err(format!("push: {name} is not a list ({})", type_name(current)));
849 }
850 let Value::Json(serde_json::Value::Array(mut arr)) = current.clone() else {
851 unreachable!("checked above")
852 };
853 arr.extend(values.iter().map(value_to_json));
854 self.set_global(name, Value::Json(serde_json::Value::Array(arr)));
855 Ok(())
856 }
857
858 pub fn contains(&self, name: &str) -> bool {
860 self.get(name).is_some()
861 }
862
863 pub fn all_names(&self) -> Vec<&str> {
865 let mut names: Vec<&str> = self
866 .frames
867 .iter()
868 .flat_map(|f| f.keys().map(|s| s.as_str()))
869 .collect();
870 names.sort();
871 names.dedup();
872 names
873 }
874
875 pub fn all(&self) -> Vec<(String, Value)> {
879 let mut result = std::collections::HashMap::new();
880 for frame in self.frames.iter() {
882 for (name, value) in frame {
883 result.insert(name.clone(), value.clone());
884 }
885 }
886 let mut pairs: Vec<_> = result.into_iter().collect();
887 pairs.sort_by(|(a, _), (b, _)| a.cmp(b));
888 pairs
889 }
890}
891
892impl Default for Scope {
893 fn default() -> Self {
894 Self::new()
895 }
896}
897
898#[cfg(test)]
899mod tests {
900 use super::*;
901
902 #[test]
903 fn new_scope_has_one_frame() {
904 let scope = Scope::new();
905 assert_eq!(scope.frames.len(), 1);
906 }
907
908 #[test]
909 fn set_and_get_variable() {
910 let mut scope = Scope::new();
911 scope.set("X", Value::Int(42));
912 assert_eq!(scope.get("X"), Some(&Value::Int(42)));
913 }
914
915 #[test]
916 fn get_nonexistent_returns_none() {
917 let scope = Scope::new();
918 assert_eq!(scope.get("MISSING"), None);
919 }
920
921 #[test]
922 fn inner_frame_shadows_outer() {
923 let mut scope = Scope::new();
924 scope.set("X", Value::Int(1));
925 scope.push_frame();
926 scope.set("X", Value::Int(2));
927 assert_eq!(scope.get("X"), Some(&Value::Int(2)));
928 scope.pop_frame();
929 assert_eq!(scope.get("X"), Some(&Value::Int(1)));
930 }
931
932 #[test]
933 fn inner_frame_can_see_outer_vars() {
934 let mut scope = Scope::new();
935 scope.set("OUTER", Value::String("visible".into()));
936 scope.push_frame();
937 assert_eq!(scope.get("OUTER"), Some(&Value::String("visible".into())));
938 }
939
940 #[test]
941 fn resolve_simple_path() {
942 let mut scope = Scope::new();
943 scope.set("NAME", Value::String("Alice".into()));
944
945 let path = VarPath::simple("NAME");
946 assert_eq!(
947 scope.resolve_path(&path),
948 Ok(Value::String("Alice".into()))
949 );
950 }
951
952 #[test]
953 fn resolve_bare_last_result_returns_exit_code() {
954 let mut scope = Scope::new();
955 scope.set_last_result(ExecResult::failure(127, "not found"));
956
957 let path = VarPath {
958 segments: vec![VarSegment::Field("?".into())],
959 };
960 assert_eq!(scope.resolve_path(&path), Ok(Value::Int(127)));
961 }
962
963 #[test]
964 fn resolve_last_result_field_access_is_rejected() {
965 let mut scope = Scope::new();
969 scope.set_last_result(ExecResult::success_with_data(
970 "1",
971 Value::Json(serde_json::json!({"count": 5})),
972 ));
973
974 let path = VarPath {
975 segments: vec![
976 VarSegment::Field("?".into()),
977 VarSegment::Field("data".into()),
978 ],
979 };
980 assert!(matches!(
981 scope.resolve_path(&path),
982 Err(PathError::Shape(_))
983 ));
984 }
985
986 #[test]
987 fn resolve_dotted_access_on_scalar_is_a_loud_error() {
988 let mut scope = Scope::new();
989 scope.set("X", Value::Int(42));
990
991 let path = VarPath {
993 segments: vec![
994 VarSegment::Field("X".into()),
995 VarSegment::Field("invalid".into()),
996 ],
997 };
998 assert!(matches!(
999 scope.resolve_path(&path),
1000 Err(PathError::Shape(_))
1001 ));
1002 }
1003
1004 #[test]
1005 fn resolve_undefined_root_is_soft() {
1006 let scope = Scope::new();
1007 let path = VarPath::simple("NOPE");
1008 assert!(matches!(
1009 scope.resolve_path(&path),
1010 Err(PathError::UndefinedRoot(_))
1011 ));
1012 }
1013
1014 fn subscripted(scope: &mut Scope, root: &str, value: serde_json::Value, seg: VarSegment) -> Result<Value, PathError> {
1021 scope.set(root, Value::Json(value));
1022 let path = VarPath {
1023 segments: vec![VarSegment::Field(root.into()), seg],
1024 };
1025 scope.resolve_path(&path)
1026 }
1027
1028 #[test]
1029 fn out_of_bounds_index_is_absence() {
1030 let mut scope = Scope::new();
1031 let r = subscripted(&mut scope, "xs", serde_json::json!([1, 2]), VarSegment::Index(9));
1032 assert!(matches!(r, Err(PathError::Absence(_))), "got: {r:?}");
1033 }
1034
1035 #[test]
1036 fn missing_record_key_is_absence() {
1037 let mut scope = Scope::new();
1038 let r = subscripted(&mut scope, "u", serde_json::json!({"name": "amy"}), VarSegment::Key("nope".into()));
1039 assert!(matches!(r, Err(PathError::Absence(_))), "got: {r:?}");
1040 }
1041
1042 #[test]
1043 fn string_key_on_a_list_is_shape() {
1044 let mut scope = Scope::new();
1045 let r = subscripted(&mut scope, "xs", serde_json::json!([1, 2]), VarSegment::Key("web".into()));
1046 assert!(matches!(r, Err(PathError::Shape(_))), "got: {r:?}");
1047 }
1048
1049 #[test]
1050 fn integer_index_on_a_record_is_shape() {
1051 let mut scope = Scope::new();
1052 let r = subscripted(&mut scope, "u", serde_json::json!({"name": "amy"}), VarSegment::Index(0));
1053 assert!(matches!(r, Err(PathError::Shape(_))), "got: {r:?}");
1054 }
1055
1056 #[test]
1057 fn subscripting_a_scalar_is_shape() {
1058 let mut scope = Scope::new();
1059 scope.set("s", Value::String("hello".into()));
1060 let path = VarPath {
1061 segments: vec![VarSegment::Field("s".into()), VarSegment::Index(0)],
1062 };
1063 assert!(matches!(scope.resolve_path(&path), Err(PathError::Shape(_))));
1064 }
1065
1066 #[test]
1067 fn unset_dynamic_key_is_undefined_root_not_absence() {
1068 let mut scope = Scope::new();
1071 let r = subscripted(
1072 &mut scope,
1073 "r",
1074 serde_json::json!({"name": "amy"}),
1075 VarSegment::Dynamic("k".into()),
1076 );
1077 assert!(matches!(r, Err(PathError::UndefinedRoot(_))), "got: {r:?}");
1078 }
1079
1080 #[test]
1081 fn contains_finds_variable() {
1082 let mut scope = Scope::new();
1083 scope.set("EXISTS", Value::Bool(true));
1084 assert!(scope.contains("EXISTS"));
1085 assert!(!scope.contains("MISSING"));
1086 }
1087
1088 #[test]
1089 fn all_names_lists_variables() {
1090 let mut scope = Scope::new();
1091 scope.set("A", Value::Int(1));
1092 scope.set("B", Value::Int(2));
1093 scope.push_frame();
1094 scope.set("C", Value::Int(3));
1095
1096 let names = scope.all_names();
1097 assert!(names.contains(&"A"));
1098 assert!(names.contains(&"B"));
1099 assert!(names.contains(&"C"));
1100 }
1101
1102 #[test]
1103 #[should_panic(expected = "cannot pop the root scope frame")]
1104 fn pop_root_frame_panics() {
1105 let mut scope = Scope::new();
1106 scope.pop_frame();
1107 }
1108
1109 #[test]
1110 fn positional_params_basic() {
1111 let mut scope = Scope::new();
1112 scope.set_positional("my_tool", vec!["arg1".into(), "arg2".into(), "arg3".into()]);
1113
1114 assert_eq!(scope.get_positional(0), Some("my_tool"));
1116 assert_eq!(scope.get_positional(1), Some("arg1"));
1118 assert_eq!(scope.get_positional(2), Some("arg2"));
1119 assert_eq!(scope.get_positional(3), Some("arg3"));
1120 assert_eq!(scope.get_positional(4), None);
1122 }
1123
1124 #[test]
1125 fn positional_params_empty() {
1126 let scope = Scope::new();
1127 assert_eq!(scope.get_positional(0), None);
1129 assert_eq!(scope.get_positional(1), None);
1130 assert_eq!(scope.arg_count(), 0);
1131 assert!(scope.all_args().is_empty());
1132 }
1133
1134 #[test]
1135 fn all_args_returns_slice() {
1136 let mut scope = Scope::new();
1137 scope.set_positional("test", vec!["a".into(), "b".into(), "c".into()]);
1138
1139 let args = scope.all_args();
1140 assert_eq!(args, &["a", "b", "c"]);
1141 }
1142
1143 #[test]
1144 fn arg_count_returns_count() {
1145 let mut scope = Scope::new();
1146 scope.set_positional("test", vec!["one".into(), "two".into()]);
1147
1148 assert_eq!(scope.arg_count(), 2);
1149 }
1150
1151 #[test]
1152 fn export_marks_variable() {
1153 let mut scope = Scope::new();
1154 scope.set("X", Value::Int(42));
1155
1156 assert!(!scope.is_exported("X"));
1157 scope.export("X");
1158 assert!(scope.is_exported("X"));
1159 }
1160
1161 #[test]
1162 fn set_exported_sets_and_exports() {
1163 let mut scope = Scope::new();
1164 scope.set_exported("PATH", Value::String("/usr/bin".into()));
1165
1166 assert!(scope.is_exported("PATH"));
1167 assert_eq!(scope.get("PATH"), Some(&Value::String("/usr/bin".into())));
1168 }
1169
1170 #[test]
1171 fn unexport_removes_export_marker() {
1172 let mut scope = Scope::new();
1173 scope.set_exported("VAR", Value::Int(1));
1174 assert!(scope.is_exported("VAR"));
1175
1176 scope.unexport("VAR");
1177 assert!(!scope.is_exported("VAR"));
1178 assert!(scope.get("VAR").is_some());
1180 }
1181
1182 #[test]
1183 fn exported_vars_returns_only_exported_with_values() {
1184 let mut scope = Scope::new();
1185 scope.set_exported("A", Value::Int(1));
1186 scope.set_exported("B", Value::Int(2));
1187 scope.set("C", Value::Int(3)); scope.export("D"); let exported = scope.exported_vars();
1191 assert_eq!(exported.len(), 2);
1192 assert_eq!(exported[0], ("A".to_string(), Value::Int(1)));
1193 assert_eq!(exported[1], ("B".to_string(), Value::Int(2)));
1194 }
1195
1196 #[test]
1197 fn exported_names_returns_sorted_names() {
1198 let mut scope = Scope::new();
1199 scope.export("Z");
1200 scope.export("A");
1201 scope.export("M");
1202
1203 let names = scope.exported_names();
1204 assert_eq!(names, vec!["A", "M", "Z"]);
1205 }
1206
1207 fn write_at(
1211 scope: &mut Scope,
1212 root: &str,
1213 segs: Vec<VarSegment>,
1214 ) -> Result<(), PathError> {
1215 let mut segments = vec![VarSegment::Field(root.into())];
1216 segments.extend(segs);
1217 scope.walk_write(&VarPath { segments }, Value::Int(0))
1218 }
1219
1220 #[test]
1221 fn walk_write_list_index_update() {
1222 let mut scope = Scope::new();
1223 scope.set("xs", Value::Json(serde_json::json!([1, 2, 3])));
1224 let path = VarPath {
1225 segments: vec![VarSegment::Field("xs".into()), VarSegment::Index(0)],
1226 };
1227 scope.walk_write(&path, Value::Int(9)).expect("write should succeed");
1228 assert_eq!(scope.get("xs"), Some(&Value::Json(serde_json::json!([9, 2, 3]))));
1229 }
1230
1231 #[test]
1232 fn walk_write_negative_index() {
1233 let mut scope = Scope::new();
1234 scope.set("xs", Value::Json(serde_json::json!([1, 2, 3])));
1235 let path = VarPath {
1236 segments: vec![VarSegment::Field("xs".into()), VarSegment::Index(-1)],
1237 };
1238 scope.walk_write(&path, Value::Int(7)).expect("write should succeed");
1239 assert_eq!(scope.get("xs"), Some(&Value::Json(serde_json::json!([1, 2, 7]))));
1240 }
1241
1242 #[test]
1243 fn walk_write_inserts_a_new_record_key() {
1244 let mut scope = Scope::new();
1245 scope.set("u", Value::Json(serde_json::json!({"port": 8080})));
1246 let path = VarPath {
1247 segments: vec![VarSegment::Field("u".into()), VarSegment::Key("host".into())],
1248 };
1249 scope
1250 .walk_write(&path, Value::String("localhost".into()))
1251 .expect("write should succeed");
1252 assert_eq!(
1253 scope.get("u"),
1254 Some(&Value::Json(serde_json::json!({"port": 8080, "host": "localhost"})))
1255 );
1256 }
1257
1258 #[test]
1259 fn walk_write_deep_path_updates_nested_key() {
1260 let mut scope = Scope::new();
1261 scope.set("s", Value::Json(serde_json::json!({"web": {"port": 8080}})));
1262 let path = VarPath {
1263 segments: vec![
1264 VarSegment::Field("s".into()),
1265 VarSegment::Key("web".into()),
1266 VarSegment::Key("port".into()),
1267 ],
1268 };
1269 scope.walk_write(&path, Value::Int(9000)).expect("write should succeed");
1270 assert_eq!(
1271 scope.get("s"),
1272 Some(&Value::Json(serde_json::json!({"web": {"port": 9000}})))
1273 );
1274 }
1275
1276 #[test]
1277 fn walk_write_out_of_bounds_index_is_absence() {
1278 let mut scope = Scope::new();
1279 scope.set("xs", Value::Json(serde_json::json!([1, 2, 3])));
1280 let r = write_at(&mut scope, "xs", vec![VarSegment::Index(9)]);
1281 assert!(matches!(r, Err(PathError::Absence(_))), "got: {r:?}");
1282 }
1283
1284 #[test]
1285 fn walk_write_missing_intermediate_is_absence_no_autoviv() {
1286 let mut scope = Scope::new();
1287 scope.set("s", Value::Json(serde_json::json!({"web": {"port": 8080}})));
1288 let r = write_at(
1289 &mut scope,
1290 "s",
1291 vec![VarSegment::Key("api".into()), VarSegment::Key("port".into())],
1292 );
1293 assert!(matches!(r, Err(PathError::Absence(_))), "got: {r:?}");
1294 assert_eq!(
1296 scope.get("s"),
1297 Some(&Value::Json(serde_json::json!({"web": {"port": 8080}})))
1298 );
1299 }
1300
1301 #[test]
1302 fn walk_write_scalar_root_is_shape() {
1303 let mut scope = Scope::new();
1304 scope.set("y", Value::String("hi".into()));
1305 let r = write_at(&mut scope, "y", vec![VarSegment::Index(0)]);
1306 assert!(matches!(r, Err(PathError::Shape(_))), "got: {r:?}");
1307 }
1308
1309 #[test]
1310 fn walk_write_undefined_root_is_undefined_root() {
1311 let mut scope = Scope::new();
1312 let r = write_at(&mut scope, "z", vec![VarSegment::Index(0)]);
1313 assert!(matches!(r, Err(PathError::UndefinedRoot(_))), "got: {r:?}");
1314 }
1315
1316 #[test]
1317 fn walk_write_slice_lvalue_is_shape() {
1318 let mut scope = Scope::new();
1319 scope.set("xs", Value::Json(serde_json::json!([1, 2, 3])));
1320 let r = write_at(&mut scope, "xs", vec![VarSegment::Slice(Some(0), Some(2))]);
1321 assert!(matches!(r, Err(PathError::Shape(_))), "got: {r:?}");
1322 }
1323
1324 #[test]
1327 fn walk_append_extends_a_list_in_place() {
1328 let mut scope = Scope::new();
1329 scope.set("xs", Value::Json(serde_json::json!(["a", "b"])));
1330 scope
1331 .walk_append("xs", vec![Value::String("c".into())])
1332 .expect("push should succeed");
1333 assert_eq!(scope.get("xs"), Some(&Value::Json(serde_json::json!(["a", "b", "c"]))));
1334 }
1335
1336 #[test]
1337 fn walk_append_undefined_target_is_a_loud_error() {
1338 let mut scope = Scope::new();
1339 let r = scope.walk_append("nope", vec![Value::Int(1)]);
1340 assert!(r.is_err(), "expected a loud error for an undefined target");
1341 }
1342
1343 #[test]
1344 fn walk_append_non_list_target_is_a_loud_error() {
1345 let mut scope = Scope::new();
1346 scope.set("y", Value::String("hi".into()));
1347 let r = scope.walk_append("y", vec![Value::Int(1)]);
1348 assert!(r.is_err(), "expected a loud error for a non-list target");
1349 }
1350}