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