Skip to main content

agent_first_data/document/
traverse.rs

1//! Core dot-path traversal for get/set operations.
2
3use crate::document::{
4    DocumentError, DocumentResult, Value,
5    keyed::{Addressing, KeyedList},
6    path::{PathStep, PatternSegment, join_path, parse_path, parse_path_pattern},
7};
8
9/// Resolve one non-numeric segment against `array`, returning the index of the
10/// single element it names.
11///
12/// Shared by the read and write walks so both answer a given address the same
13/// way — and so the refusals stay in one place: an array nothing claims is
14/// [`DocumentError::UnregisteredArray`], no match is
15/// [`DocumentError::SlugNotFound`], and several matches is
16/// [`DocumentError::AmbiguousMatch`] rather than the first one.
17/// `-` is not a name but the append position, which only `set` writes to,
18/// and only as the last segment of its path. It is reserved on every array
19/// and in every verb, so an element whose slug happens to be `-` is reached by
20/// index instead: were it a name anywhere, `get a.-` would read an element
21/// that `set a.-` then appends beside. Reporting it as an unnamed element
22/// would send the caller looking for a naming rule.
23pub(crate) fn append_position_refused(prefix: &[String], last: bool) -> DocumentError {
24    let detail = if last {
25        format!(
26            "`-` names the append position after the last element of `{}`, which is only \
27             valid as the last segment of a `set` path; address an existing element by index",
28            join_path(prefix)
29        )
30    } else {
31        format!(
32            "`-` names the append position of `{}` and can only be the last segment of a \
33             path; address an existing element by index",
34            join_path(prefix)
35        )
36    };
37    DocumentError::PathSyntax { detail }
38}
39
40/// `-` was written under a path that does not exist yet. Appending needs an
41/// array to append to, and inventing one would mean guessing the container
42/// type, so the caller creates it first.
43fn append_target_missing(prefix: &[String]) -> DocumentError {
44    let path = join_path(prefix);
45    DocumentError::PathSyntax {
46        detail: format!(
47            "`-` appends to an existing array and `{path}` does not exist; create it first \
48             (set `{path}` to `[]` with `--value-type json`), then append"
49        ),
50    }
51}
52
53fn resolve_named_element(
54    array: &[Value],
55    segment: &str,
56    prefix: &[String],
57    last: bool,
58    addressing: Addressing<'_>,
59) -> DocumentResult<usize> {
60    if segment == "-" {
61        return Err(append_position_refused(prefix, last));
62    }
63    // A caller's explicit declaration outranks a format-wide rule: it names one
64    // array on purpose, so it is the more specific statement about this one.
65    if let Some(registration) = addressing
66        .keyed_lists
67        .iter()
68        .find(|list| keyed_prefix_matches(list, prefix))
69    {
70        let hits = array
71            .iter()
72            .enumerate()
73            .filter(|(_, element)| {
74                element.get(registration.slug_field).and_then(Value::as_str) == Some(segment)
75            })
76            .map(|(index, _)| index)
77            .collect();
78        return resolve_unique_hit(hits, segment, &join_path(prefix));
79    }
80
81    let Some(rule) = addressing.array_rule else {
82        return Err(DocumentError::UnregisteredArray {
83            path: join_path(prefix),
84        });
85    };
86
87    let hits: Vec<usize> = array
88        .iter()
89        .enumerate()
90        .filter(|(_, element)| rule.matches(element, segment))
91        .map(|(index, _)| index)
92        .collect();
93    resolve_unique_hit(hits, segment, &join_path(prefix))
94}
95
96fn resolve_unique_hit(hits: Vec<usize>, segment: &str, prefix: &str) -> DocumentResult<usize> {
97    match hits.as_slice() {
98        [] => Err(DocumentError::SlugNotFound {
99            prefix: prefix.to_string(),
100            slug: segment.to_string(),
101        }),
102        [only] => Ok(*only),
103        several => Err(DocumentError::AmbiguousMatch {
104            prefix: prefix.to_string(),
105            segment: segment.to_string(),
106            indices: several.to_vec(),
107        }),
108    }
109}
110
111fn index_with_slug_check(
112    array: &[Value],
113    segment: &str,
114    prefix: &[String],
115    addressing: Addressing<'_>,
116) -> DocumentResult<Option<usize>> {
117    let Some(index) = array_index(segment)? else {
118        return Ok(None);
119    };
120    let field = addressing
121        .keyed_lists
122        .iter()
123        .find(|list| keyed_prefix_matches(list, prefix))
124        .map(|list| list.slug_field)
125        .or_else(|| {
126            addressing
127                .array_rule
128                .filter(|rule| rule.match_kind == super::MatchKind::Exact)
129                .map(|rule| rule.field)
130        });
131    if let Some(field) = field {
132        let mut indices: Vec<_> = array
133            .iter()
134            .enumerate()
135            .filter(|(_, element)| element.get(field).and_then(Value::as_str) == Some(segment))
136            .map(|(index, _)| index)
137            .collect();
138        if indices.iter().any(|hit| *hit != index) {
139            if index < array.len() && !indices.contains(&index) {
140                indices.push(index);
141                indices.sort_unstable();
142            }
143            return Err(DocumentError::AmbiguousMatch {
144                prefix: join_path(prefix),
145                segment: segment.to_string(),
146                indices,
147            });
148        }
149    }
150    Ok(Some(index))
151}
152
153/// Parse an array index without letting decimal overflow fall through to named
154/// lookup.
155///
156/// `str::parse::<usize>()` alone cannot distinguish "not a number" from "a
157/// number too large for this platform". The former may be a slug; the latter
158/// is still lexically an index and must fail as one rather than unexpectedly
159/// matching document content.
160pub(super) fn array_index(segment: &str) -> DocumentResult<Option<usize>> {
161    if segment.is_empty() || !segment.bytes().all(|byte| byte.is_ascii_digit()) {
162        return Ok(None);
163    }
164    segment
165        .parse::<usize>()
166        .map(Some)
167        .map_err(|_| DocumentError::PathSyntax {
168            detail: "array index exceeds the platform index range".to_string(),
169        })
170}
171
172/// A node a path resolved to, with the structural route that reached it.
173#[derive(Debug, Clone, PartialEq)]
174pub struct Located<'a> {
175    /// Object keys and array levels from the root to `value`.
176    pub steps: Vec<PathStep>,
177    /// The node itself.
178    pub value: &'a Value,
179}
180
181/// Resolve a document path and return its node and structural route.
182pub fn locate<'a>(
183    root: &'a Value,
184    path: &str,
185    addressing: Addressing<'_>,
186) -> DocumentResult<Located<'a>> {
187    let (steps, value) = locate_with_route(root, path, addressing)?;
188    Ok(Located {
189        steps,
190        value: value?,
191    })
192}
193
194/// Resolve a path, retaining structural steps even when the target is absent.
195///
196/// After a missing field or an unexpected scalar, the unresolved suffix is
197/// judged conservatively as field names. A segment addressing a known array
198/// is always an element, even when no matching element exists.
199pub fn locate_with_route<'a>(
200    root: &'a Value,
201    path: &str,
202    addressing: Addressing<'_>,
203) -> DocumentResult<(Vec<PathStep>, DocumentResult<&'a Value>)> {
204    let segments = parse_path(path)?;
205    let mut steps = Vec::with_capacity(segments.len());
206    let target = traverse_route(root, path, &segments, addressing, &mut steps);
207    steps.extend(segments[steps.len()..].iter().cloned().map(PathStep::Field));
208    Ok((steps, target))
209}
210
211fn traverse_route<'a>(
212    root: &'a Value,
213    path: &str,
214    segments: &[String],
215    addressing: Addressing<'_>,
216    steps: &mut Vec<PathStep>,
217) -> DocumentResult<&'a Value> {
218    let mut current = root;
219    // The caller's own segments so far: what a keyed-list registration and
220    // every error message are written against.
221    let mut accumulated_prefix: Vec<String> = Vec::new();
222
223    for (seg_idx, current_seg) in segments.iter().enumerate() {
224        match current {
225            Value::Object(obj) => {
226                steps.push(PathStep::Field(current_seg.clone()));
227                let Some(next) = obj.get(current_seg.as_str()) else {
228                    return Err(DocumentError::UnknownSegment {
229                        path: path.to_string(),
230                        segment: current_seg.clone(),
231                    });
232                };
233                current = next;
234            }
235            Value::Array(arr) => {
236                steps.push(PathStep::Element);
237                let index =
238                    match index_with_slug_check(arr, current_seg, &accumulated_prefix, addressing)?
239                    {
240                        Some(index) => {
241                            if index >= arr.len() {
242                                return Err(DocumentError::IndexOutOfBounds {
243                                    path: join_path(&accumulated_prefix),
244                                    index,
245                                    len: arr.len(),
246                                });
247                            }
248                            index
249                        }
250                        None => resolve_named_element(
251                            arr,
252                            current_seg,
253                            &accumulated_prefix,
254                            seg_idx + 1 == segments.len(),
255                            addressing,
256                        )?,
257                    };
258                current = &arr[index];
259            }
260            _ => {
261                return Err(DocumentError::NotTraversable {
262                    path: join_path(&accumulated_prefix),
263                    got: current.kind_name().to_string(),
264                });
265            }
266        }
267        accumulated_prefix.push(current_seg.clone());
268    }
269
270    Ok(current)
271}
272
273/// Get a value at the given dot-path: [`locate`] without the route.
274pub fn get_path_ref<'a>(
275    root: &'a Value,
276    path: &str,
277    addressing: Addressing<'_>,
278) -> DocumentResult<&'a Value> {
279    Ok(locate(root, path, addressing)?.value)
280}
281
282/// Get a cloned value at the given dot-path.
283pub fn get_path(root: &Value, path: &str, addressing: Addressing<'_>) -> DocumentResult<Value> {
284    Ok(get_path_ref(root, path, addressing)?.clone())
285}
286
287/// Rewrite `path` into the equivalent index-only address for `root`.
288///
289/// Content addressing is something only the parsed value can answer, and the
290/// source-preserving writers never see it: each backend re-walks the original
291/// text by path, and nothing in `identities.me` tells a TOML editor which
292/// element `me` is. So a write resolves the address once, here, where the whole
293/// document is in hand, and hands the backends the canonical `identities.0`.
294/// The alternative — teaching six backends to match on content — would give
295/// each its own chance to disagree with the read walk about what an address
296/// means.
297///
298/// Resolution stops at the first segment the document does not have and copies
299/// the rest verbatim, because `set` creates missing object parents and a node
300/// that does not exist yet cannot be addressed by its content anyway. Whatever
301/// is wrong with the tail is then the writer's error to report, unchanged.
302///
303/// Two prefixes are tracked because they answer different questions: the
304/// *semantic* one (the caller's own segments) is what a [`KeyedList`]
305/// registration is matched against, so a registration keeps meaning what it
306/// meant on the read path, while the *canonical* one (resolved indices) is what
307/// gets returned.
308pub fn resolve_path(
309    root: &Value,
310    path: &str,
311    addressing: Addressing<'_>,
312) -> DocumentResult<String> {
313    if path.is_empty() {
314        return Ok(String::new());
315    }
316
317    let segments = parse_path(path)?;
318    let mut current = root;
319    let mut semantic: Vec<String> = Vec::new();
320    let mut canonical: Vec<String> = Vec::with_capacity(segments.len());
321
322    for (idx, segment) in segments.iter().enumerate() {
323        let copy_rest = |canonical: &mut Vec<String>| {
324            canonical.extend(segments[idx..].iter().cloned());
325        };
326        match current {
327            Value::Object(object) => match object.get(segment.as_str()) {
328                Some(next) => {
329                    canonical.push(segment.clone());
330                    semantic.push(segment.clone());
331                    current = next;
332                }
333                None => {
334                    copy_rest(&mut canonical);
335                    break;
336                }
337            },
338            Value::Array(array) => {
339                if segment == "-" && idx + 1 == segments.len() {
340                    canonical.push(segment.clone());
341                    break;
342                }
343                let index = match index_with_slug_check(array, segment, &semantic, addressing)? {
344                    Some(index) => index,
345                    None => resolve_named_element(
346                        array,
347                        segment,
348                        &semantic,
349                        idx + 1 == segments.len(),
350                        addressing,
351                    )?,
352                };
353                let Some(next) = array.get(index) else {
354                    copy_rest(&mut canonical);
355                    break;
356                };
357                canonical.push(index.to_string());
358                semantic.push(segment.clone());
359                current = next;
360            }
361            _ => {
362                copy_rest(&mut canonical);
363                break;
364            }
365        }
366    }
367
368    Ok(join_path(&canonical))
369}
370
371/// What [`expand_path_pattern`] does when the container a wildcard stands in
372/// is not there.
373#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
374pub enum MissingContainer {
375    /// Fail: an absent container (or any segment before it) is the lookup's
376    /// own miss, and a `null` one is [`DocumentError::NullContainer`].
377    #[default]
378    Error,
379    /// Expand to nothing. Covers exactly what [`DocumentError::is_address_miss`]
380    /// covers, plus a `null` container; a scalar where a container is needed is
381    /// still [`DocumentError::NotContainer`].
382    Empty,
383}
384
385/// Resolve a path pattern against `root` into the concrete paths it names.
386///
387/// A bare `*` segment (see [`parse_path_pattern`]) stands for every child of
388/// the container at that point: an object's keys in document order, or an
389/// array's indices. The results are ordinary paths in the one grammar — a star
390/// key in one comes back escaped as `\*` — so each reads back through
391/// [`locate`] or [`get_path`]. A pattern without a wildcard is returned exactly
392/// as written, one path.
393///
394/// Only the containers a wildcard expands are resolved here. Segments after
395/// the last wildcard are copied, not checked, so a child that lacks the field
396/// the pattern goes on to name still yields its path, and reading that path is
397/// where the miss is reported — with any fallback the caller has for it.
398pub fn expand_path_pattern(
399    root: &Value,
400    pattern: &str,
401    addressing: Addressing<'_>,
402    missing: MissingContainer,
403) -> DocumentResult<Vec<String>> {
404    let segments = parse_path_pattern(pattern)?;
405    if !segments
406        .iter()
407        .any(|segment| matches!(segment, PatternSegment::Wildcard))
408    {
409        return Ok(vec![pattern.to_string()]);
410    }
411    let skip_missing = missing == MissingContainer::Empty;
412    let mut frontier = vec![Vec::<String>::new()];
413    for segment in &segments {
414        let mut next = Vec::new();
415        for mut prefix in frontier {
416            if let PatternSegment::Key(key) = segment {
417                prefix.push(key.clone());
418                next.push(prefix);
419                continue;
420            }
421            let here = join_path(&prefix);
422            let target = if prefix.is_empty() {
423                root
424            } else {
425                match get_path_ref(root, &here, addressing) {
426                    Ok(target) => target,
427                    Err(err) if skip_missing && err.is_address_miss() => continue,
428                    Err(err) => return Err(err),
429                }
430            };
431            let children: Vec<String> = match target {
432                Value::Null if skip_missing => continue,
433                Value::Null => return Err(DocumentError::NullContainer { path: here }),
434                Value::Object(map) => map.keys().cloned().collect(),
435                Value::Array(items) => (0..items.len()).map(|index| index.to_string()).collect(),
436                scalar => {
437                    return Err(DocumentError::NotContainer {
438                        path: here,
439                        got: scalar.kind_name().to_string(),
440                    });
441                }
442            };
443            for child in children {
444                let mut extended = prefix.clone();
445                extended.push(child);
446                next.push(extended);
447            }
448        }
449        frontier = next;
450    }
451    Ok(frontier
452        .iter()
453        .map(|segments| join_path(segments))
454        .collect())
455}
456
457/// Set a value at the given dot-path. `value` is inserted as-is at the leaf —
458/// no coercion happens here; callers that accept CLI strings (e.g. the
459/// `afdata` binary) construct the typed `Value` first, via
460/// [`crate::document::coerce::value_from_type`] (an explicit `--value-type`)
461/// or a bare `Value::String` (zero coercion), before calling this.
462pub fn set_path(
463    root: &mut Value,
464    path: &str,
465    value: &Value,
466    addressing: Addressing<'_>,
467) -> DocumentResult<()> {
468    if path.is_empty() {
469        return Err(DocumentError::EmptyPath);
470    }
471
472    let segments = parse_path(path)?;
473    set_path_recursive(root, &segments, 0, &mut Vec::new(), addressing, value)
474}
475
476fn set_path_recursive(
477    current: &mut Value,
478    segments: &[String],
479    idx: usize,
480    accumulated_prefix: &mut Vec<String>,
481    addressing: Addressing<'_>,
482    value: &Value,
483) -> DocumentResult<()> {
484    if idx >= segments.len() {
485        return Err(DocumentError::EmptyPath);
486    }
487
488    let current_seg = segments[idx].as_str();
489    let is_last = idx == segments.len() - 1;
490
491    match current {
492        Value::Object(obj) => {
493            // Path parsing makes dotted keys explicit via `\\.`.
494            let key_to_use = current_seg.to_string();
495
496            let segments_to_consume = 1;
497
498            if is_last {
499                // At leaf: insert the typed value directly.
500                obj.insert(key_to_use, value.clone());
501                Ok(())
502            } else {
503                // Not at leaf: ensure key exists and recurse
504                let next_idx = idx + segments_to_consume;
505                if next_idx >= segments.len() {
506                    return Err(DocumentError::EmptyPath);
507                }
508
509                accumulated_prefix.push(key_to_use.clone());
510
511                // Use entry API to avoid double borrow
512                use std::collections::btree_map::Entry;
513                match obj.entry(key_to_use) {
514                    Entry::Occupied(mut ent) => set_path_recursive(
515                        ent.get_mut(),
516                        segments,
517                        next_idx,
518                        accumulated_prefix,
519                        addressing,
520                        value,
521                    ),
522                    Entry::Vacant(ent) => {
523                        // `-` appends to an array that exists. A container this call
524                        // would invent is an object, and an object holding a literal
525                        // `-` key is not what the caller asked for.
526                        if segments[next_idx] == "-" {
527                            return Err(append_target_missing(accumulated_prefix));
528                        }
529                        let mut new_obj = Value::Object(Default::default());
530                        let result = set_path_recursive(
531                            &mut new_obj,
532                            segments,
533                            next_idx,
534                            accumulated_prefix,
535                            addressing,
536                            value,
537                        );
538                        if result.is_ok() {
539                            ent.insert(new_obj);
540                        }
541                        result
542                    }
543                }
544            }
545        }
546        Value::Array(arr) => {
547            if current_seg == "-" && is_last {
548                arr.push(value.clone());
549                return Ok(());
550            }
551            if let Some(arr_idx) =
552                index_with_slug_check(arr, current_seg, accumulated_prefix, addressing)?
553            {
554                if arr_idx >= arr.len() {
555                    return Err(DocumentError::IndexOutOfBounds {
556                        path: join_path(accumulated_prefix),
557                        index: arr_idx,
558                        len: arr.len(),
559                    });
560                }
561                if is_last {
562                    arr[arr_idx] = value.clone();
563                    Ok(())
564                } else {
565                    accumulated_prefix.push(current_seg.to_string());
566                    set_path_recursive(
567                        &mut arr[arr_idx],
568                        segments,
569                        idx + 1,
570                        accumulated_prefix,
571                        addressing,
572                        value,
573                    )
574                }
575            } else {
576                let elem_idx = resolve_named_element(
577                    arr,
578                    current_seg,
579                    accumulated_prefix,
580                    is_last,
581                    addressing,
582                )?;
583                if is_last {
584                    Err(DocumentError::UnsupportedOperation {
585                        format: "keyed list".to_string(),
586                        operation: "set".to_string(),
587                        detail:
588                            "a keyed-list slug resolves to an element; set a child field instead"
589                                .to_string(),
590                    })
591                } else {
592                    accumulated_prefix.push(current_seg.to_string());
593                    set_path_recursive(
594                        &mut arr[elem_idx],
595                        segments,
596                        idx + 1,
597                        accumulated_prefix,
598                        addressing,
599                        value,
600                    )
601                }
602            }
603        }
604        _ => Err(DocumentError::NotTraversable {
605            path: join_path(accumulated_prefix),
606            got: current.kind_name().to_string(),
607        }),
608    }
609}
610
611pub(crate) fn keyed_prefix_matches(
612    registration: &KeyedList<'_>,
613    semantic_prefix: &[String],
614) -> bool {
615    if registration.prefix.is_empty() {
616        return semantic_prefix.is_empty();
617    }
618    crate::document::parse_path(registration.prefix)
619        .ok()
620        .is_some_and(|segments| segments == semantic_prefix)
621}
622
623/// Remove the key at the given dot-path from its parent object.
624///
625/// This is the free-fn "remove a key" verb (paired with keyed-element removal
626/// via [`crate::document::remove_keyed`]).
627pub fn unset_path(root: &mut Value, path: &str) -> DocumentResult<()> {
628    if path.is_empty() {
629        return Err(DocumentError::EmptyPath);
630    }
631    let segments = parse_path(path)?;
632    unset_path_recursive(root, &segments, 0, &mut Vec::new())
633}
634
635fn unset_path_recursive(
636    current: &mut Value,
637    segments: &[String],
638    idx: usize,
639    accumulated_prefix: &mut Vec<String>,
640) -> DocumentResult<()> {
641    if idx >= segments.len() {
642        return Err(DocumentError::EmptyPath);
643    }
644    let current_seg = segments[idx].as_str();
645    let is_last = idx == segments.len() - 1;
646
647    match current {
648        Value::Object(obj) => {
649            let key_to_use = current_seg.to_string();
650            let segments_to_consume = 1;
651
652            if is_last {
653                if obj.remove(&key_to_use).is_none() {
654                    return Err(DocumentError::PathNotFound { path: key_to_use });
655                }
656                Ok(())
657            } else {
658                let next_idx = idx + segments_to_consume;
659                accumulated_prefix.push(key_to_use.clone());
660                if let Some(next) = obj.get_mut(&key_to_use) {
661                    unset_path_recursive(next, segments, next_idx, accumulated_prefix)
662                } else {
663                    Err(DocumentError::PathNotFound {
664                        path: join_path(accumulated_prefix),
665                    })
666                }
667            }
668        }
669        Value::Array(arr) => {
670            if let Some(arr_idx) = array_index(current_seg)? {
671                if arr_idx >= arr.len() {
672                    return Err(DocumentError::IndexOutOfBounds {
673                        path: join_path(accumulated_prefix),
674                        index: arr_idx,
675                        len: arr.len(),
676                    });
677                }
678                if is_last {
679                    arr.remove(arr_idx);
680                    Ok(())
681                } else {
682                    accumulated_prefix.push(current_seg.to_string());
683                    unset_path_recursive(&mut arr[arr_idx], segments, idx + 1, accumulated_prefix)
684                }
685            } else if current_seg == "-" {
686                Err(append_position_refused(accumulated_prefix, is_last))
687            } else {
688                Err(DocumentError::UnregisteredArray {
689                    path: join_path(accumulated_prefix),
690                })
691            }
692        }
693        _ => Err(DocumentError::NotTraversable {
694            path: join_path(accumulated_prefix),
695            got: current.kind_name().to_string(),
696        }),
697    }
698}
699
700#[cfg(test)]
701mod tests {
702    #![allow(
703        clippy::unwrap_used,
704        clippy::panic,
705        clippy::expect_used,
706        clippy::bool_assert_comparison
707    )]
708    use super::*;
709
710    fn make_test_object() -> Value {
711        let mut root = Value::Object(Default::default());
712        let mut imap = Value::Object(Default::default());
713        imap.as_object_mut().unwrap().insert(
714            "host".to_string(),
715            Value::String("mail.example.com".to_string()),
716        );
717        imap.as_object_mut()
718            .unwrap()
719            .insert("port".to_string(), Value::Integer(993));
720
721        root.as_object_mut()
722            .unwrap()
723            .insert("imap".to_string(), imap);
724
725        root
726    }
727
728    #[test]
729    fn test_get_path_simple() {
730        let root = make_test_object();
731        let result = get_path(&root, "imap.host", Addressing::INDEX_ONLY).unwrap();
732        assert_eq!(result.as_str().unwrap(), "mail.example.com");
733    }
734
735    #[test]
736    fn test_get_path_integer() {
737        let root = make_test_object();
738        let result = get_path(&root, "imap.port", Addressing::INDEX_ONLY).unwrap();
739        assert_eq!(result.as_integer().unwrap(), 993);
740    }
741
742    #[test]
743    fn test_set_path_new_key() {
744        let mut root = make_test_object();
745        set_path(
746            &mut root,
747            "imap.tls",
748            &Value::Bool(true),
749            Addressing::INDEX_ONLY,
750        )
751        .unwrap();
752
753        let result = get_path(&root, "imap.tls", Addressing::INDEX_ONLY).unwrap();
754        assert_eq!(result.as_bool().unwrap(), true);
755    }
756
757    #[test]
758    fn test_set_path_overwrite() {
759        let mut root = make_test_object();
760        set_path(
761            &mut root,
762            "imap.port",
763            &Value::Integer(587),
764            Addressing::INDEX_ONLY,
765        )
766        .unwrap();
767
768        let result = get_path(&root, "imap.port", Addressing::INDEX_ONLY).unwrap();
769        assert_eq!(result.as_integer().unwrap(), 587);
770    }
771
772    #[test]
773    fn test_set_path_array_value() {
774        let mut root = Value::Object(Default::default());
775        let value = Value::Array(vec![
776            Value::String("dev".to_string()),
777            Value::String("staging".to_string()),
778        ]);
779        set_path(&mut root, "tags", &value, Addressing::INDEX_ONLY).unwrap();
780
781        let result = get_path(&root, "tags", Addressing::INDEX_ONLY).unwrap();
782        let arr = result.as_array().unwrap();
783        assert_eq!(arr.len(), 2);
784    }
785
786    fn make_steps_object() -> Value {
787        // { "steps": [{"name": "a", "port": 1}, {"name": "b", "port": 2}] }
788        let mut root = Value::Object(Default::default());
789        let mut s0 = Value::Object(Default::default());
790        s0.as_object_mut()
791            .unwrap()
792            .insert("name".to_string(), Value::String("a".to_string()));
793        s0.as_object_mut()
794            .unwrap()
795            .insert("port".to_string(), Value::Integer(1));
796        let mut s1 = Value::Object(Default::default());
797        s1.as_object_mut()
798            .unwrap()
799            .insert("name".to_string(), Value::String("b".to_string()));
800        s1.as_object_mut()
801            .unwrap()
802            .insert("port".to_string(), Value::Integer(2));
803        root.as_object_mut()
804            .unwrap()
805            .insert("steps".to_string(), Value::Array(vec![s0, s1]));
806        root
807    }
808
809    #[test]
810    fn test_get_path_numeric_index() {
811        let root = make_steps_object();
812        let name = get_path(&root, "steps.0.name", Addressing::INDEX_ONLY).unwrap();
813        assert_eq!(name.as_str().unwrap(), "a");
814        let port = get_path(&root, "steps.1.port", Addressing::INDEX_ONLY).unwrap();
815        assert_eq!(port.as_integer().unwrap(), 2);
816    }
817
818    #[test]
819    fn test_set_path_numeric_index() {
820        let mut root = make_steps_object();
821        set_path(
822            &mut root,
823            "steps.0.port",
824            &Value::Integer(99),
825            Addressing::INDEX_ONLY,
826        )
827        .unwrap();
828        let result = get_path(&root, "steps.0.port", Addressing::INDEX_ONLY).unwrap();
829        assert_eq!(result.as_integer().unwrap(), 99);
830        // other element unchanged
831        let other = get_path(&root, "steps.1.port", Addressing::INDEX_ONLY).unwrap();
832        assert_eq!(other.as_integer().unwrap(), 2);
833    }
834
835    #[test]
836    fn test_get_path_index_out_of_bounds() {
837        let root = make_steps_object();
838        let err = get_path(&root, "steps.5.name", Addressing::INDEX_ONLY).unwrap_err();
839        assert!(matches!(
840            err,
841            DocumentError::IndexOutOfBounds {
842                index: 5,
843                len: 2,
844                ..
845            }
846        ));
847    }
848
849    #[test]
850    fn test_remove_path_numeric_index() {
851        let mut root = make_steps_object();
852        unset_path(&mut root, "steps.0").unwrap();
853        let arr = get_path(&root, "steps", Addressing::INDEX_ONLY).unwrap();
854        let arr = arr.as_array().unwrap();
855        assert_eq!(arr.len(), 1);
856        assert_eq!(arr[0].get("name").unwrap().as_str().unwrap(), "b");
857    }
858
859    #[test]
860    fn named_root_array_keeps_a_semantic_prefix_for_nested_keyed_lists() {
861        let mut child = Value::Object(Default::default());
862        child
863            .as_object_mut()
864            .unwrap()
865            .insert("id".to_string(), Value::String("beta".to_string()));
866        child
867            .as_object_mut()
868            .unwrap()
869            .insert("value".to_string(), Value::Integer(1));
870
871        let mut parent = Value::Object(Default::default());
872        parent
873            .as_object_mut()
874            .unwrap()
875            .insert("id".to_string(), Value::String("alpha".to_string()));
876        parent
877            .as_object_mut()
878            .unwrap()
879            .insert("children".to_string(), Value::Array(vec![child]));
880
881        let mut root = Value::Array(vec![parent]);
882        let keyed = [
883            KeyedList {
884                prefix: "",
885                slug_field: "id",
886            },
887            KeyedList {
888                prefix: "alpha.children",
889                slug_field: "id",
890            },
891        ];
892        let addressing = Addressing::keyed(&keyed);
893
894        assert_eq!(
895            get_path(&root, "alpha.children.beta.value", addressing).unwrap(),
896            Value::Integer(1)
897        );
898        set_path(
899            &mut root,
900            "alpha.children.beta.value",
901            &Value::Integer(2),
902            addressing,
903        )
904        .unwrap();
905        assert_eq!(
906            get_path(&root, "alpha.children.beta.value", addressing).unwrap(),
907            Value::Integer(2)
908        );
909    }
910
911    #[test]
912    fn locate_reports_the_route_with_elements_as_positions() {
913        let root = make_steps_object();
914        let keyed = [KeyedList {
915            prefix: "steps",
916            slug_field: "name",
917        }];
918        let by_name = locate(&root, "steps.b.port", Addressing::keyed(&keyed)).unwrap();
919        let by_index = locate(&root, "steps.1.port", Addressing::INDEX_ONLY).unwrap();
920        assert_eq!(by_name, by_index);
921        assert_eq!(
922            by_name.steps,
923            vec![
924                PathStep::Field("steps".to_string()),
925                PathStep::Element,
926                PathStep::Field("port".to_string()),
927            ]
928        );
929        assert_eq!(by_name.value, &Value::Integer(2));
930    }
931
932    #[test]
933    fn expand_path_pattern_names_each_child_and_leaves_the_tail_to_the_read() {
934        let root = make_steps_object();
935        assert_eq!(
936            expand_path_pattern(
937                &root,
938                "steps.*.name",
939                Addressing::INDEX_ONLY,
940                MissingContainer::Error
941            )
942            .unwrap(),
943            vec!["steps.0.name".to_string(), "steps.1.name".to_string()]
944        );
945        // The tail after the last wildcard is copied, not checked.
946        assert_eq!(
947            expand_path_pattern(
948                &root,
949                "steps.*.absent",
950                Addressing::INDEX_ONLY,
951                MissingContainer::Error
952            )
953            .unwrap()
954            .len(),
955            2
956        );
957        // No wildcard: the pattern itself, as written.
958        assert_eq!(
959            expand_path_pattern(
960                &root,
961                "nope.x",
962                Addressing::INDEX_ONLY,
963                MissingContainer::Error
964            )
965            .unwrap(),
966            vec!["nope.x".to_string()]
967        );
968        // An absent container is the lookup's miss, or nothing when allowed.
969        let miss = expand_path_pattern(
970            &root,
971            "nope.*",
972            Addressing::INDEX_ONLY,
973            MissingContainer::Error,
974        )
975        .unwrap_err();
976        assert!(miss.is_address_miss());
977        assert!(
978            expand_path_pattern(
979                &root,
980                "nope.*",
981                Addressing::INDEX_ONLY,
982                MissingContainer::Empty
983            )
984            .unwrap()
985            .is_empty()
986        );
987        // A scalar is never a container, whatever the policy.
988        let scalar = expand_path_pattern(
989            &root,
990            "steps.0.port.*",
991            Addressing::INDEX_ONLY,
992            MissingContainer::Empty,
993        )
994        .unwrap_err();
995        assert_eq!(scalar.code(), "document_not_container");
996        // A null one is empty only when allowed.
997        let mut with_null = root.clone();
998        with_null
999            .as_object_mut()
1000            .unwrap()
1001            .insert("unset".to_string(), Value::Null);
1002        assert_eq!(
1003            expand_path_pattern(
1004                &with_null,
1005                "unset.*",
1006                Addressing::INDEX_ONLY,
1007                MissingContainer::Error
1008            )
1009            .unwrap_err()
1010            .code(),
1011            "document_null_value"
1012        );
1013        assert!(
1014            expand_path_pattern(
1015                &with_null,
1016                "unset.*",
1017                Addressing::INDEX_ONLY,
1018                MissingContainer::Empty
1019            )
1020            .unwrap()
1021            .is_empty()
1022        );
1023    }
1024
1025    #[test]
1026    fn oversized_decimal_array_segment_never_falls_through_to_a_slug() {
1027        let oversized = format!("{}0", usize::MAX);
1028        let mut item = Value::Object(Default::default());
1029        item.as_object_mut()
1030            .unwrap()
1031            .insert("id".to_string(), Value::String(oversized.clone()));
1032        let root = Value::Array(vec![item]);
1033        let keyed = [KeyedList {
1034            prefix: "",
1035            slug_field: "id",
1036        }];
1037
1038        let error = get_path(&root, &oversized, Addressing::keyed(&keyed)).unwrap_err();
1039        assert!(matches!(error, DocumentError::PathSyntax { .. }));
1040    }
1041
1042    #[test]
1043    fn dotted_key_and_nested_path_keep_distinct_keyed_registrations() {
1044        let item = |field: &str, slug: &str| {
1045            let mut value = Value::Object(Default::default());
1046            value
1047                .as_object_mut()
1048                .unwrap()
1049                .insert(field.to_string(), Value::String(slug.to_string()));
1050            value
1051        };
1052
1053        let mut nested = Value::Object(Default::default());
1054        nested.as_object_mut().unwrap().insert(
1055            "b".to_string(),
1056            Value::Array(vec![item("nested_id", "nested")]),
1057        );
1058
1059        let mut root = Value::Object(Default::default());
1060        root.as_object_mut().unwrap().insert(
1061            "a.b".to_string(),
1062            Value::Array(vec![item("dotted_id", "dotted")]),
1063        );
1064        root.as_object_mut()
1065            .unwrap()
1066            .insert("a".to_string(), nested);
1067
1068        let keyed = [
1069            KeyedList {
1070                prefix: r"a\.b",
1071                slug_field: "dotted_id",
1072            },
1073            KeyedList {
1074                prefix: "a.b",
1075                slug_field: "nested_id",
1076            },
1077        ];
1078        let addressing = Addressing::keyed(&keyed);
1079
1080        assert_eq!(
1081            get_path(&root, r"a\.b.dotted.dotted_id", addressing).unwrap(),
1082            Value::String("dotted".to_string())
1083        );
1084        assert_eq!(
1085            get_path(&root, "a.b.nested.nested_id", addressing).unwrap(),
1086            Value::String("nested".to_string())
1087        );
1088    }
1089}