agent_first_data/document/path.rs
1//! The single path grammar used by every traversal operation.
2//!
3//! A dot separates segments. `\.` embeds a dot in a key, `\\` embeds a
4//! backslash, and `\*` embeds a star. Every other escape is rejected so a path
5//! is reversible.
6//!
7//! A bare `*` segment is reserved: it means "each child here" to the commands
8//! that accept a pattern, and [`parse_path`] refuses it rather than reading it
9//! as a key. `*` is a legal key in JSON, so [`join_path`] escapes it — a
10//! document carrying one is still addressable, as `\*`.
11//!
12//! A segment may be empty, because `""` is a legal key in JSON and YAML — npm
13//! writes one into every `package-lock.json` as the root package. Rejecting it
14//! did not make it unreachable, only unspeakable: [`join_path`] still rendered
15//! `["packages", ""]` as `packages.`, so `paths` emitted addresses that `value`
16//! and `set` then refused, and the reversibility this grammar exists to
17//! guarantee did not hold.
18//!
19//! The one sequence with no spelling is `[""]` on its own: it renders as the
20//! empty string, which names no path at all. A `""` key at the document root is
21//! therefore unaddressable, and that is the only hole left.
22
23use crate::document::{DocumentError, DocumentResult};
24
25pub fn parse_path(path: &str) -> DocumentResult<Vec<String>> {
26 if path.is_empty() {
27 return Err(DocumentError::EmptyPath);
28 }
29 let mut segments = Vec::new();
30 let mut segment = String::new();
31 let mut escaped = false;
32 // `\*` and `*` both parse to the same string, so the reservation below has
33 // to know which one was written.
34 let mut wrote_bare_star = false;
35 let mut literal = false;
36 for character in path.chars() {
37 if escaped {
38 match character {
39 '.' | '\\' | '*' => {
40 segment.push(character);
41 literal = true;
42 }
43 other => {
44 return Err(DocumentError::PathSyntax {
45 detail: format!("invalid escape `\\{other}`"),
46 });
47 }
48 }
49 escaped = false;
50 } else {
51 match character {
52 '\\' => escaped = true,
53 '.' => {
54 if segment == "*" && !literal {
55 wrote_bare_star = true;
56 }
57 segments.push(std::mem::take(&mut segment));
58 literal = false;
59 }
60 other => segment.push(other),
61 }
62 }
63 }
64 if escaped {
65 return Err(DocumentError::PathSyntax {
66 detail: "trailing path escape".to_string(),
67 });
68 }
69 if segment == "*" && !literal {
70 wrote_bare_star = true;
71 }
72 segments.push(segment);
73 // A bare `*` means "each child" wherever a path is written, so refuse it
74 // here rather than let it read as a key in one command and expand in
75 // another. The literal spelling is `\*`, which reaches this point as the
76 // same string and must still be accepted.
77 if wrote_bare_star {
78 return Err(DocumentError::PathSyntax {
79 detail: "a bare `*` segment is a pattern; write `\\*` for a literal star key, or use \
80 `values`, which expands patterns"
81 .to_string(),
82 });
83 }
84 Ok(segments)
85}
86
87pub fn join_path(segments: &[String]) -> String {
88 segments
89 .iter()
90 .map(|segment| {
91 segment
92 .replace('\\', "\\\\")
93 .replace('.', "\\.")
94 .replace('*', "\\*")
95 })
96 .collect::<Vec<_>>()
97 .join(".")
98}
99
100/// One structural step from a value's root to a node inside it: an object key,
101/// or the position of an array element.
102///
103/// A written path and the route it resolves to are different things. The
104/// grammar above spells an array element by index or by an identifier its
105/// [`Addressing`](crate::document::Addressing) matches against the element's
106/// content (`servers.reviewer.port`); either way the route records
107/// [`PathStep::Element`]. An identifier is data
108/// inside the element, not a field name on the route, so nothing that judges a
109/// route by its keys — [`Redactor::value_at`](crate::Redactor::value_at)
110/// above all — ever sees it. Produced by
111/// [`locate`](crate::document::locate).
112#[derive(Debug, Clone, PartialEq, Eq, Hash)]
113pub enum PathStep {
114 /// The member of an object with this exact (unescaped) key.
115 Field(String),
116 /// An array element, independent of how it was addressed.
117 Element,
118}
119
120/// One segment of a path that may address many nodes.
121#[derive(Debug, Clone, PartialEq, Eq)]
122pub enum PatternSegment {
123 /// A literal key or array index.
124 Key(String),
125 /// A bare `*`: every child of the container at this point.
126 Wildcard,
127}
128
129/// Parse a path in which a bare `*` segment means "each child here".
130///
131/// Reading one field across a collection was three steps — enumerate the
132/// children, append the field to each address, then read them — and the middle
133/// step was string surgery on this grammar's own output. A pattern says it
134/// directly: `package.*.name`.
135///
136/// A literal star is still addressable as `\*`, so no document becomes
137/// unreachable by reserving the bare form.
138///
139/// This only parses; [`expand_path_pattern`](crate::document::expand_path_pattern)
140/// resolves a pattern against a document into the concrete paths it names.
141pub fn parse_path_pattern(path: &str) -> DocumentResult<Vec<PatternSegment>> {
142 if path.is_empty() {
143 return Err(DocumentError::EmptyPath);
144 }
145 let mut segments = Vec::new();
146 let mut segment = String::new();
147 let mut escaped = false;
148 let mut literal = false;
149 for character in path.chars() {
150 if escaped {
151 match character {
152 '.' | '\\' | '*' => {
153 segment.push(character);
154 literal = true;
155 }
156 other => {
157 return Err(DocumentError::PathSyntax {
158 detail: format!("invalid escape `\\{other}`"),
159 });
160 }
161 }
162 escaped = false;
163 } else {
164 match character {
165 '\\' => escaped = true,
166 '.' => {
167 segments.push(finish_pattern_segment(
168 std::mem::take(&mut segment),
169 literal,
170 ));
171 literal = false;
172 }
173 other => segment.push(other),
174 }
175 }
176 }
177 if escaped {
178 return Err(DocumentError::PathSyntax {
179 detail: "trailing path escape".to_string(),
180 });
181 }
182 segments.push(finish_pattern_segment(segment, literal));
183 Ok(segments)
184}
185
186fn finish_pattern_segment(segment: String, literal: bool) -> PatternSegment {
187 if segment == "*" && !literal {
188 PatternSegment::Wildcard
189 } else {
190 PatternSegment::Key(segment)
191 }
192}
193
194#[cfg(test)]
195mod tests {
196 use super::*;
197
198 /// The property this grammar exists to have: every key sequence has one
199 /// spelling, and that spelling reads back as the same sequence.
200 #[test]
201 fn every_key_sequence_round_trips_through_its_spelling() {
202 let cases: &[&[&str]] = &[
203 &["packages", "", "version"],
204 &["packages", ""],
205 &["", "a"],
206 &["a", "", "", "b"],
207 &["plain"],
208 &["a.dotted.key", "b"],
209 &["back\\slash"],
210 &["node_modules/@esbuild/darwin-arm64"],
211 ];
212 for segments in cases {
213 let owned: Vec<String> = segments.iter().map(|s| (*s).to_string()).collect();
214 let spelling = join_path(&owned);
215 let parsed = parse_path(&spelling)
216 .unwrap_or_else(|error| panic!("{owned:?} spelled `{spelling}`: {error}"));
217 assert_eq!(parsed, owned, "spelled `{spelling}`");
218 }
219 }
220
221 #[test]
222 fn an_empty_segment_is_a_key_not_an_error() {
223 // npm writes `""` as the root package of every package-lock.json.
224 // Rejecting it did not make it unreachable, only unspeakable.
225 assert_eq!(
226 parse_path("packages..version").unwrap(),
227 vec!["packages".to_string(), String::new(), "version".to_string()]
228 );
229 assert_eq!(
230 parse_path("packages.").unwrap(),
231 vec!["packages".to_string(), String::new()]
232 );
233 assert_eq!(
234 parse_path(".leading").unwrap(),
235 vec![String::new(), "leading".to_string()]
236 );
237 }
238
239 #[test]
240 fn a_star_key_survives_the_wildcard_reservation() {
241 // `*` is a legal JSON key. Reserving the bare form for patterns must
242 // not make a document carrying one unaddressable — the same mistake
243 // the empty-segment rejection made.
244 assert_eq!(join_path(&["*".to_string()]), r"\*");
245 assert_eq!(parse_path(r"\*").unwrap(), vec!["*".to_string()]);
246 assert_eq!(
247 parse_path(r"a.\*.b").unwrap(),
248 vec!["a".to_string(), "*".to_string(), "b".to_string()]
249 );
250 // Round-trip, which is the property that matters.
251 let segments = vec!["a".to_string(), "*".to_string()];
252 assert_eq!(parse_path(&join_path(&segments)).unwrap(), segments);
253 }
254
255 #[test]
256 fn a_bare_star_is_reserved_for_patterns() {
257 // One spelling, one meaning: it must not read as a key here and expand
258 // somewhere else.
259 assert!(parse_path("*").is_err());
260 assert!(parse_path("package.*.name").is_err());
261 // The pattern parser is where it means something.
262 assert_eq!(
263 parse_path_pattern("package.*.name").unwrap(),
264 vec![
265 PatternSegment::Key("package".to_string()),
266 PatternSegment::Wildcard,
267 PatternSegment::Key("name".to_string()),
268 ]
269 );
270 // And escaped, it is a key even there.
271 assert_eq!(
272 parse_path_pattern(r"a.\*").unwrap(),
273 vec![
274 PatternSegment::Key("a".to_string()),
275 PatternSegment::Key("*".to_string()),
276 ]
277 );
278 }
279
280 #[test]
281 fn the_empty_string_still_names_no_path() {
282 // The one sequence with no spelling. `[""]` renders as "", which is
283 // how a caller says "I gave you no path" — so a `""` key at the
284 // document root stays unaddressable, and that is the only hole.
285 assert!(matches!(parse_path(""), Err(DocumentError::EmptyPath)));
286 assert_eq!(join_path(&[String::new()]), "");
287 }
288
289 #[test]
290 fn malformed_escapes_are_still_refused() {
291 assert!(parse_path(r"trailing\").is_err());
292 assert!(parse_path(r"bad\qescape").is_err());
293 }
294}