Skip to main content

agent_first_data/document/
keyed.rs

1//! KeyedList operations for slug-based array access.
2
3use crate::document::{DocumentError, DocumentResult, Value, join_path};
4
5/// Declares that an array at `prefix` is keyed by `slug_field`.
6///
7/// Example: `KeyedList { prefix: "identities", slug_field: "identity" }`
8/// enables path `identities.me.email` to find the element where
9/// `element["identity"] == "me"`, then read/write `element["email"]`.
10#[derive(Debug, Clone, Copy)]
11pub struct KeyedList<'a> {
12    pub prefix: &'a str,
13    pub slug_field: &'a str,
14}
15
16/// How a path segment resolves against an array.
17///
18/// ASCII-decimal segments address indices. An exact slug that names a
19/// different element makes such a segment ambiguous. Overflow is an error.
20/// Named segments have two possible sources, tried in this order:
21///
22/// - [`keyed_lists`](Self::keyed_lists) — the caller's own declarations, e.g.
23///   "the array at `identities` is keyed by each element's `identity` field".
24///   A JSON or TOML document does not say this about itself, so only the
25///   caller can, and it names one exact array by path.
26/// - [`array_rule`](Self::array_rule) — the *format's* rule, for a format whose
27///   value is a tree afdata synthesized and therefore knows the shape of. Only
28///   Markdown has one today; it applies to every array in the document rather
29///   than to one named path.
30///
31/// With neither, a non-numeric segment against an array is
32/// [`DocumentError::UnregisteredArray`]
33/// — afdata will not scan an array it was told nothing about.
34#[derive(Debug, Clone, Copy, Default)]
35pub struct Addressing<'a> {
36    pub keyed_lists: &'a [KeyedList<'a>],
37    pub array_rule: Option<ArrayRule<'a>>,
38}
39
40impl<'a> Addressing<'a> {
41    /// Indices only: no keyed lists, no format rule.
42    pub const INDEX_ONLY: Addressing<'static> = Addressing {
43        keyed_lists: &[],
44        array_rule: None,
45    };
46
47    /// Caller-declared keyed lists, with no format rule.
48    #[must_use]
49    pub const fn keyed(keyed_lists: &'a [KeyedList<'a>]) -> Self {
50        Addressing {
51            keyed_lists,
52            array_rule: None,
53        }
54    }
55
56    /// The same addressing plus a format's built-in array rule.
57    #[must_use]
58    pub const fn with_array_rule(self, array_rule: Option<ArrayRule<'a>>) -> Self {
59        Addressing { array_rule, ..self }
60    }
61}
62
63/// A format's built-in rule for resolving a non-numeric segment against an
64/// array: compare the segment to [`field`](Self::field) on each element.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub struct ArrayRule<'a> {
67    /// Element field the segment is compared against. An element lacking it,
68    /// or holding a non-string there, simply does not match.
69    pub field: &'a str,
70    pub match_kind: MatchKind,
71}
72
73/// How an [`ArrayRule`] compares a segment to an element's field.
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub enum MatchKind {
76    /// The field equals the segment.
77    Exact,
78    /// The field contains the segment after Unicode lowercase conversion — so
79    /// `h2.look`
80    /// finds `## A Quick Look`. Prose headings are long and get reworded;
81    /// a memorable word out of one is a far steadier address than either its
82    /// position or its full text.
83    ///
84    /// Exactly one element must match. Several is
85    /// [`DocumentError::AmbiguousMatch`],
86    /// never the first one.
87    Contains,
88}
89
90impl ArrayRule<'_> {
91    /// Whether `element` matches `segment` under this rule.
92    #[must_use]
93    pub fn matches(&self, element: &Value, segment: &str) -> bool {
94        let Some(field) = element.get(self.field).and_then(Value::as_str) else {
95            return false;
96        };
97        match self.match_kind {
98            MatchKind::Exact => field == segment,
99            // An empty segment is not an address. `contains("")` is true for
100            // every element, so without this a path built by interpolation —
101            // which is how both consumers build theirs — resolves to a
102            // confident wrong answer on any single-element array, and only
103            // becomes an error once a second element exists. `Exact` already
104            // rejects it by construction (nothing equals ""), so this keeps
105            // the two modes agreeing about what is addressable.
106            MatchKind::Contains if segment.is_empty() => false,
107            MatchKind::Contains => field.to_lowercase().contains(&segment.to_lowercase()),
108        }
109    }
110}
111
112/// Path segments a keyed-list prefix names, where the empty prefix means the
113/// document root is itself the keyed array.
114///
115/// `parse_path` rejects an empty path, which is right for an address but wrong
116/// for this prefix: `traverse::keyed_prefix_matches` has always accepted
117/// `KeyedList { prefix: "" }`, so a root array could be read by slug while
118/// `add`/`remove` answered `EmptyPath` for the very same registration.
119fn keyed_prefix_segments(prefix: &str) -> DocumentResult<Vec<String>> {
120    if prefix.is_empty() {
121        return Ok(Vec::new());
122    }
123    crate::document::parse_path(prefix)
124}
125
126/// Validate that a slug can be used as an array path segment.
127pub fn validate_array_slug(prefix: &str, slug: &str) -> DocumentResult<()> {
128    if slug == "-" || slug.bytes().all(|byte| byte.is_ascii_digit()) {
129        return Err(DocumentError::UnaddressableSlug {
130            prefix: prefix.to_string(),
131        });
132    }
133    Ok(())
134}
135
136/// Add a new element to a keyed list.
137///
138/// The new element is built in three layers:
139/// 1. `seed` fields (if provided) — default template values
140/// 2. `{ slug_field: slug }` — always set, overrides any slug value in seed
141/// 3. explicit `fields` — override both seed and slug (except the slug field)
142pub fn add_keyed(
143    root: &mut Value,
144    prefix: &str,
145    slug: &str,
146    keyed_lists: &[KeyedList<'_>],
147    seed: Option<&Value>,
148    fields: &[(String, Value)],
149) -> DocumentResult<()> {
150    // Resolve the prefix through the single path grammar so top-level and nested
151    // (dotted or escaped) prefixes are all matched by their normalized segments.
152    let segments = keyed_prefix_segments(prefix)?;
153    let registration = keyed_lists
154        .iter()
155        .find(|list| crate::document::keyed_prefix_matches(list, &segments))
156        .ok_or_else(|| DocumentError::UnregisteredArray {
157            path: prefix.to_string(),
158        })?;
159    validate_array_slug(prefix, slug)?;
160    if fields.iter().any(|(key, _)| key == registration.slug_field) {
161        return Err(DocumentError::InvalidArgument {
162            detail: format!(
163                "field `{}` cannot override slug field",
164                registration.slug_field
165            ),
166        });
167    }
168    add_keyed_segments(
169        root,
170        &segments,
171        0,
172        slug,
173        seed,
174        fields,
175        registration.slug_field,
176    )
177}
178
179/// Remove the unique element named by `slug` and return its former index.
180///
181/// The index lets a source-preserving backend remove the exact same element
182/// from its syntax tree without independently repeating the identity lookup.
183pub fn remove_keyed(
184    root: &mut Value,
185    prefix: &str,
186    slug: &str,
187    keyed_lists: &[KeyedList<'_>],
188) -> DocumentResult<usize> {
189    let segments = keyed_prefix_segments(prefix)?;
190    let registered = keyed_lists
191        .iter()
192        .any(|list| crate::document::keyed_prefix_matches(list, &segments));
193    if !registered {
194        return Err(DocumentError::UnregisteredArray {
195            path: prefix.to_string(),
196        });
197    }
198
199    remove_keyed_segments(root, &segments, 0, slug, keyed_lists)
200}
201
202fn keyed_index<'a>(
203    items: &'a mut [Value],
204    segment: &str,
205    path: &[String],
206) -> DocumentResult<&'a mut Value> {
207    super::traverse::array_index(segment)?
208        .and_then(|index| items.get_mut(index))
209        .ok_or_else(|| DocumentError::PathNotFound {
210            path: join_path(path),
211        })
212}
213
214fn add_keyed_segments(
215    current: &mut Value,
216    segments: &[String],
217    index: usize,
218    slug: &str,
219    seed: Option<&Value>,
220    fields: &[(String, Value)],
221    slug_field: &str,
222) -> DocumentResult<()> {
223    if let Some(segment) = segments.get(index)
224        && let Value::Array(items) = current
225    {
226        let next = keyed_index(items, segment, segments)?;
227        return add_keyed_segments(next, segments, index + 1, slug, seed, fields, slug_field);
228    }
229    if index + 1 < segments.len() {
230        let Value::Object(object) = current else {
231            return Err(DocumentError::NotTraversable {
232                path: join_path(&segments[..index]),
233                got: current.kind_name().to_string(),
234            });
235        };
236        let next = object
237            .entry(segments[index].clone())
238            .or_insert_with(|| Value::Object(Default::default()));
239        return add_keyed_segments(next, segments, index + 1, slug, seed, fields, slug_field);
240    }
241    let array = if index == segments.len() {
242        current
243    } else {
244        let Value::Object(object) = current else {
245            return Err(DocumentError::NotTraversable {
246                path: join_path(&segments[..index]),
247                got: current.kind_name().to_string(),
248            });
249        };
250        object
251            .entry(segments[index].clone())
252            .or_insert_with(|| Value::Array(Vec::new()))
253    };
254    let Value::Array(array) = array else {
255        return Err(DocumentError::NotTraversable {
256            path: join_path(segments),
257            got: array.kind_name().to_string(),
258        });
259    };
260    if array.iter().any(|entry| {
261        entry
262            .as_object()
263            .and_then(|object| object.get(slug_field))
264            .and_then(Value::as_str)
265            == Some(slug)
266    }) {
267        return Err(DocumentError::SlugAlreadyExists {
268            prefix: join_path(segments),
269            slug: slug.to_string(),
270        });
271    }
272    let mut element = Value::Object(Default::default());
273    let object = element
274        .as_object_mut()
275        .ok_or_else(|| DocumentError::NotTraversable {
276            path: join_path(segments),
277            got: "failed to create object".to_string(),
278        })?;
279    if let Some(seed) = seed.and_then(Value::as_object) {
280        for (key, value) in seed {
281            if key != slug_field {
282                object.insert(key.clone(), value.clone());
283            }
284        }
285    }
286    object.insert(slug_field.to_string(), Value::String(slug.to_string()));
287    for (key, value) in fields {
288        object.insert(key.clone(), value.clone());
289    }
290    array.push(element);
291    Ok(())
292}
293
294fn remove_keyed_segments(
295    current: &mut Value,
296    segments: &[String],
297    index: usize,
298    slug: &str,
299    keyed_lists: &[KeyedList<'_>],
300) -> DocumentResult<usize> {
301    if let Some(segment) = segments.get(index)
302        && let Value::Array(items) = current
303    {
304        let next = keyed_index(items, segment, segments)?;
305        return remove_keyed_segments(next, segments, index + 1, slug, keyed_lists);
306    }
307    if index + 1 < segments.len() {
308        let Value::Object(object) = current else {
309            return Err(DocumentError::NotTraversable {
310                path: join_path(&segments[..index]),
311                got: current.kind_name().to_string(),
312            });
313        };
314        let next = object
315            .get_mut(&segments[index])
316            .ok_or_else(|| DocumentError::PathNotFound {
317                path: join_path(segments),
318            })?;
319        return remove_keyed_segments(next, segments, index + 1, slug, keyed_lists);
320    }
321    let target = if index == segments.len() {
322        current
323    } else {
324        let Value::Object(object) = current else {
325            return Err(DocumentError::NotTraversable {
326                path: join_path(&segments[..index]),
327                got: current.kind_name().to_string(),
328            });
329        };
330        object
331            .get_mut(&segments[index])
332            .ok_or_else(|| DocumentError::PathNotFound {
333                path: join_path(segments),
334            })?
335    };
336    let Value::Array(array) = target else {
337        return Err(DocumentError::NotTraversable {
338            path: join_path(segments),
339            got: target.kind_name().to_string(),
340        });
341    };
342    let registration = keyed_lists
343        .iter()
344        .find(|list| crate::document::keyed_prefix_matches(list, segments))
345        .ok_or_else(|| DocumentError::UnregisteredArray {
346            path: join_path(segments),
347        })?;
348    let matches: Vec<usize> = array
349        .iter()
350        .enumerate()
351        .filter(|(_, entry)| {
352            entry
353                .as_object()
354                .and_then(|object| object.get(registration.slug_field))
355                .and_then(Value::as_str)
356                == Some(slug)
357        })
358        .map(|(index, _)| index)
359        .collect();
360    let index = match matches.as_slice() {
361        [] => {
362            return Err(DocumentError::SlugNotFound {
363                prefix: join_path(segments),
364                slug: slug.to_string(),
365            });
366        }
367        [index] => *index,
368        _ => {
369            return Err(DocumentError::AmbiguousMatch {
370                prefix: join_path(segments),
371                segment: slug.to_string(),
372                indices: matches,
373            });
374        }
375    };
376    array.remove(index);
377    Ok(index)
378}
379
380#[cfg(test)]
381mod tests {
382    #![allow(clippy::unwrap_used, clippy::panic)]
383    use super::*;
384
385    #[test]
386    fn test_add_keyed() {
387        let mut root = Value::Object(Default::default());
388        let keyed = [KeyedList {
389            prefix: "identities",
390            slug_field: "identity",
391        }];
392
393        root.as_object_mut()
394            .unwrap()
395            .insert("identities".to_string(), Value::Array(vec![]));
396
397        add_keyed(
398            &mut root,
399            "identities",
400            "me",
401            &keyed,
402            None,
403            &[
404                (
405                    "email".to_string(),
406                    Value::String("me@example.com".to_string()),
407                ),
408                ("name".to_string(), Value::String("Me".to_string())),
409            ],
410        )
411        .unwrap();
412
413        let arr = root.get("identities").unwrap().as_array().unwrap();
414        assert_eq!(arr.len(), 1);
415
416        let elem = &arr[0];
417        assert_eq!(elem.get("identity").unwrap().as_str().unwrap(), "me");
418        assert_eq!(
419            elem.get("email").unwrap().as_str().unwrap(),
420            "me@example.com"
421        );
422    }
423
424    #[test]
425    fn test_add_keyed_with_seed() {
426        let mut root = Value::Object(Default::default());
427        let keyed = [KeyedList {
428            prefix: "identities",
429            slug_field: "identity",
430        }];
431        root.as_object_mut()
432            .unwrap()
433            .insert("identities".to_string(), Value::Array(vec![]));
434
435        let mut seed_obj = std::collections::BTreeMap::new();
436        seed_obj.insert("enabled".to_string(), Value::Bool(true));
437        seed_obj.insert("role".to_string(), Value::String("user".to_string()));
438        seed_obj.insert(
439            "email".to_string(),
440            Value::String("default@example.com".to_string()),
441        );
442        let seed = Value::Object(seed_obj);
443
444        add_keyed(
445            &mut root,
446            "identities",
447            "alice",
448            &keyed,
449            Some(&seed),
450            &[(
451                "email".to_string(),
452                Value::String("alice@example.com".to_string()),
453            )], // overrides seed
454        )
455        .unwrap();
456
457        let elem = &root.get("identities").unwrap().as_array().unwrap()[0];
458        assert_eq!(elem.get("identity").unwrap().as_str().unwrap(), "alice");
459        assert_eq!(elem.get("role").unwrap().as_str().unwrap(), "user"); // from seed
460        assert!(elem.get("enabled").unwrap().as_bool().unwrap()); // from seed
461        assert_eq!(
462            elem.get("email").unwrap().as_str().unwrap(),
463            "alice@example.com"
464        ); // fields override seed
465    }
466
467    #[test]
468    fn test_remove_keyed() {
469        let mut root = Value::Object(Default::default());
470        let keyed = [KeyedList {
471            prefix: "identities",
472            slug_field: "identity",
473        }];
474
475        let mut elem1 = Value::Object(Default::default());
476        elem1
477            .as_object_mut()
478            .unwrap()
479            .insert("identity".to_string(), Value::String("me".to_string()));
480
481        let mut elem2 = Value::Object(Default::default());
482        elem2
483            .as_object_mut()
484            .unwrap()
485            .insert("identity".to_string(), Value::String("other".to_string()));
486
487        root.as_object_mut()
488            .unwrap()
489            .insert("identities".to_string(), Value::Array(vec![elem1, elem2]));
490
491        let removed_index = remove_keyed(&mut root, "identities", "me", &keyed).unwrap();
492
493        assert_eq!(removed_index, 0);
494        let arr = root.get("identities").unwrap().as_array().unwrap();
495        assert_eq!(arr.len(), 1);
496        assert_eq!(arr[0].get("identity").unwrap().as_str().unwrap(), "other");
497    }
498
499    #[test]
500    fn test_remove_keyed_refuses_duplicate_slug_without_mutating() {
501        let item = |email: &str| {
502            let mut value = Value::Object(Default::default());
503            let object = value.as_object_mut().unwrap();
504            object.insert("identity".to_string(), Value::String("me".to_string()));
505            object.insert("email".to_string(), Value::String(email.to_string()));
506            value
507        };
508        let mut original = Value::Object(Default::default());
509        original.as_object_mut().unwrap().insert(
510            "identities".to_string(),
511            Value::Array(vec![item("first"), item("second")]),
512        );
513        let mut root = original.clone();
514        let keyed = [KeyedList {
515            prefix: "identities",
516            slug_field: "identity",
517        }];
518
519        let error = remove_keyed(&mut root, "identities", "me", &keyed).unwrap_err();
520
521        assert!(matches!(
522            error,
523            DocumentError::AmbiguousMatch {
524                prefix,
525                segment,
526                indices
527            } if prefix == "identities"
528                && segment == "me"
529                && indices == vec![0, 1]
530        ));
531        assert_eq!(root, original);
532    }
533
534    #[test]
535    fn test_add_and_remove_keyed_nested_dotted_prefix() {
536        // A plain dotted (unescaped) nested prefix must route through the same
537        // normalized-segment matcher as top-level and escaped prefixes.
538        let mut root = Value::Object(Default::default());
539        let keyed = [KeyedList {
540            prefix: "cfg.users",
541            slug_field: "uid",
542        }];
543
544        add_keyed(
545            &mut root,
546            "cfg.users",
547            "bob",
548            &keyed,
549            None,
550            &[("role".to_string(), Value::String("dev".to_string()))],
551        )
552        .unwrap();
553
554        let arr = root
555            .get("cfg")
556            .unwrap()
557            .get("users")
558            .unwrap()
559            .as_array()
560            .unwrap();
561        assert_eq!(arr.len(), 1);
562        assert_eq!(arr[0].get("uid").unwrap().as_str().unwrap(), "bob");
563        assert_eq!(arr[0].get("role").unwrap().as_str().unwrap(), "dev");
564
565        remove_keyed(&mut root, "cfg.users", "bob", &keyed).unwrap();
566        let arr = root
567            .get("cfg")
568            .unwrap()
569            .get("users")
570            .unwrap()
571            .as_array()
572            .unwrap();
573        assert!(arr.is_empty());
574    }
575}
576
577#[cfg(test)]
578mod root_array_tests {
579    #![allow(clippy::unwrap_used)]
580    use super::*;
581    use crate::document::{Addressing, get_path};
582    use std::collections::BTreeMap;
583
584    fn element(id: &str) -> Value {
585        Value::Object(BTreeMap::from([(
586            "id".to_string(),
587            Value::String(id.to_string()),
588        )]))
589    }
590
591    #[test]
592    fn a_root_array_reads_and_edits_through_the_same_registration() {
593        // `KeyedList { prefix: "" }` has always resolved on the read walk;
594        // `add`/`remove` rejected it with `EmptyPath` because they ran the
595        // prefix through `parse_path`, which refuses an empty address. One
596        // registration must mean one thing to both.
597        let lists = [KeyedList {
598            prefix: "",
599            slug_field: "id",
600        }];
601        let mut root = Value::Array(vec![element("a"), element("b")]);
602
603        assert_eq!(
604            get_path(&root, "a.id", Addressing::keyed(&lists)).unwrap(),
605            Value::String("a".to_string())
606        );
607        assert_eq!(remove_keyed(&mut root, "", "a", &lists).unwrap(), 0);
608        assert_eq!(root.as_array().map(Vec::len), Some(1));
609
610        add_keyed(&mut root, "", "c", &lists, None, &[]).unwrap();
611        assert_eq!(
612            get_path(&root, "c.id", Addressing::keyed(&lists)).unwrap(),
613            Value::String("c".to_string())
614        );
615
616        // An unregistered root array is still refused, not scanned.
617        let mut bare = Value::Array(vec![element("a")]);
618        assert_eq!(
619            remove_keyed(&mut bare, "", "a", &[]).unwrap_err().code(),
620            "document_path_not_found"
621        );
622    }
623}