Debian Codegraph @

src/inspect/traverse.rs

raw symbols SCIP
1 //! Ways of traversing the AST-like structure of [`Inspectable`]s.
2 //!
3 //! Refer to the [documentation here][crate::inspect#traversing].
4
5 use smallvec::SmallVec;
6
7 use crate::inspect::*;
8
9 /// A `Step` in a search path, which selects what next traversal
10 /// will be applied to an [`Inspectable`] tree.
11 ///
12 /// A search path is a list of Steps.
13 #[derive(Debug, Clone)]
14 pub enum Step<'a> {
15 /// Searches for a child, which is either an [`Inspectable`] or a [Dict
16 /// Entry][crate::inspect::InDictEntry].
17 /// Only finds the first child matching the specific condition.
18 Search(Search<'a>),
19
20 /// Access the nth child of a List or Dict.
21 Nth(usize),
22
23 /// Accesses a Dict Entry with the given key.
24 Entry(&'a [u8]),
25
26 /// Assume current item is an Dict Entry, access the key.
27 Key,
28
29 /// Assume current item is an Dict Entry, access the value.
30 Value,
31 }
32
33 /// An object that represents what to search for in a [`Step::Search`].
34 #[derive(Debug, Clone)]
35 pub enum Search<'a> {
36 /// Search for a String with this exact value.
37 ByteString(&'a [u8]),
38
39 /// Search for a Dict Entry that has this exact key.
40 DictKey(&'a [u8]),
41
42 /// Search for this exact integer.
43 Int(Cow<'a, str>),
44 }
45
46 type Path<'a> = SmallVec<[Step<'a>; 20]>;
47
48 /// A builder for a path. A path is a list of [`Step`]s undertaken to traverse
49 /// an [`Inspectable`] AST.
50 ///
51 /// Use the methods provided to add new steps to the path, then provide a reference
52 /// to the [`PathBuilder`] to one of these methods:
53 /// * [`Inspectable::find`]
54 /// * [`Inspectable::find_ref`]
55 /// * [`Inspectable::clone_and_mutate`]
56 /// * [`Inspectable::mutate`]
57 ///
58 /// Unlike the standard build pattern, no `.build()` function is needed to reify
59 /// the builder.
60 ///
61 /// The methods named `into_*` all take ownership of the PathBuilder, add the step,
62 /// then return the builder. This reduces memory allocation, but may be inconvenient.
63 ///
64 /// The methods without the `into_` prefix will create a clone of the PathBuilder,
65 /// add the step to that clone, then return the clone. This may be more convenient
66 /// if you are building multiple paths that all start with the same steps.
67 ///
68 /// The builder can contain up to 20 steps before it needs to allocate. For fuzzing,
69 /// manually building structures using the [`Inspectable`] constructor methods is
70 /// recommended instead of mutating existing [`Inspectable`]s.
71 #[derive(Debug, Clone)]
72 pub struct PathBuilder<'a> {
73 pub steps: Path<'a>,
74 }
75
76 impl<'obj, 'pb, 'step> PathBuilder<'pb>
77 where
78 'step: 'pb,
79 {
80 #[allow(clippy::new_without_default)]
81 pub fn new() -> Self {
82 PathBuilder {
83 steps: Default::default(),
84 }
85 }
86
87 /// Descend into a specific item in a list or entry in a dict, given its index.
88 ///
89 /// For dicts, MUST be followed by a call to one of: [`.key`][PathBuilder::key],
90 /// [`.into_key`][PathBuilder::into_key], [`.value`][PathBuilder::value],
91 /// or [`.into_value`][PathBuilder::into_value].
92 pub fn into_nth(mut self, idx: usize) -> Self {
93 self.steps.push(Step::Nth(idx));
94 self
95 }
96
97 /// Descend into a specific item in a list or entry in a dict, given its index.
98 ///
99 /// For dicts, MUST be followed by a call to one of: [`.key`][PathBuilder::key],
100 /// [`.into_key`][PathBuilder::into_key], [`.value`][PathBuilder::value],
101 /// or [`.into_value`][PathBuilder::into_value].
102 pub fn nth(&'obj self, idx: usize) -> Self {
103 let next = self.clone();
104 next.into_nth(idx)
105 }
106
107 /// Access a Dict Entry that has the given key byte string.
108 ///
109 /// MUST be followed by a call to one of: [`.key`][PathBuilder::key],
110 /// [`.into_key`][PathBuilder::into_key], [`.value`][PathBuilder::value],
111 /// or [`.into_value`][PathBuilder::into_value].
112 pub fn into_entry(mut self, entry_key: &'step [u8]) -> PathBuilder<'pb> {
113 self.steps.push(Step::Entry(entry_key));
114 self
115 }
116
117 /// Access a Dict Entry that has the given key byte string.
118 ///
119 /// MUST be followed by a call to one of: [`.key`][PathBuilder::key],
120 /// [`.into_key`][PathBuilder::into_key], [`.value`][PathBuilder::value],
121 /// or [`.into_value`][PathBuilder::into_value].
122 pub fn entry(&'obj self, entry_key: &'step [u8]) -> PathBuilder<'pb> {
123 let next = self.clone();
124 next.into_entry(entry_key)
125 }
126
127 /// Access the key part of a Dict Entry.
128 pub fn into_key(mut self) -> Self {
129 self.steps.push(Step::Key);
130 self
131 }
132
133 /// Access the key part of a Dict Entry.
134 pub fn key(&'obj self) -> Self {
135 let next = self.clone();
136 next.into_key()
137 }
138
139 /// Access the value part of a Dict Entry.
140 pub fn into_value(mut self) -> Self {
141 self.steps.push(Step::Value);
142 self
143 }
144
145 /// Access the value part of a Dict Entry.
146 pub fn value(&'obj self) -> Self {
147 let next = self.clone();
148 next.into_value()
149 }
150
151 /// Search for byte strings that are not dict keys.
152 pub fn into_search_bytestring(mut self, bytestring: &'step [u8]) -> PathBuilder<'pb> {
153 self.steps
154 .push(Step::Search(Search::ByteString(bytestring)));
155 self
156 }
157
158 /// Search for byte strings that are not dict keys.
159 pub fn search_bytestring(&'obj self, bytestring: &'step [u8]) -> PathBuilder<'pb> {
160 let next = self.clone();
161 next.into_search_bytestring(bytestring)
162 }
163
164 /// Search for Dict Entries that have the given key.
165 ///
166 /// MUST be followed by a call to one of: [`.key`][PathBuilder::key],
167 /// [`.into_key`][PathBuilder::into_key], [`.value`][PathBuilder::value],
168 /// or [`.into_value`][PathBuilder::into_value].
169 pub fn into_search_entry(mut self, dict_key: &'step [u8]) -> PathBuilder<'pb> {
170 self.steps.push(Step::Search(Search::DictKey(dict_key)));
171 self
172 }
173
174 /// Search for Dict Entries that have the given key.
175 ///
176 /// MUST be followed by a call to one of: [`.key`][PathBuilder::key],
177 /// [`.into_key`][PathBuilder::into_key], [`.value`][PathBuilder::value],
178 /// or [`.into_value`][PathBuilder::into_value].
179 pub fn search_entry(&'obj self, dict_key: &'step [u8]) -> PathBuilder<'pb> {
180 let next = self.clone();
181 next.into_search_entry(dict_key)
182 }
183
184 /// Search for an integer, provided as a string slice.
185 pub fn into_search_int(mut self, number: &'step str) -> PathBuilder<'pb> {
186 self.steps.push(Step::Search(Search::Int(number.into())));
187 self
188 }
189
190 /// Search for an integer, provided as a string slice.
191 pub fn search_int(&'obj self, number: &'step str) -> PathBuilder<'pb> {
192 let next = self.clone();
193 next.into_search_int(number)
194 }
195
196 /// Search for an integer, this function converts an i64 to a string slice for you.
197 pub fn into_search_int_i64(mut self, number: i64) -> PathBuilder<'pb> {
198 self.steps
199 .push(Step::Search(Search::Int(number.to_string().into())));
200 self
201 }
202
203 /// Search for an integer, this function converts an i64 to a string slice for you.
204 pub fn search_int_i64(&'obj self, number: i64) -> PathBuilder<'pb> {
205 let next = self.clone();
206 next.into_search_int_i64(number)
207 }
208 }
209
210 impl<'obj, 'ser, 'pb, 'pbobj> Inspectable<'ser> {
211 /// Gets a mutable reference to the Inspectable pointed to by the given path.
212 /// Panics if no Inspectable matches the given path.
213 pub fn find(&'obj mut self, path: &'pbobj PathBuilder<'pb>) -> &'obj mut Inspectable<'ser> {
214 let res = self.find_impl(&path.steps, 0);
215 match res {
216 None => panic!("Path did not resolve to an Inspectable: {:?}", path),
217 Some(x) => x,
218 }
219 }
220
221 /// Gets a reference to the Inspectable pointed to by the given path.
222 /// Panics if no Inspectable matches the given path.
223 pub fn find_ref(&'obj self, path: &'pbobj PathBuilder<'pb>) -> &'obj Inspectable<'ser> {
224 let res = self.find_ref_impl(&path.steps, 0);
225 match res {
226 None => panic!("Path did not resolve to an Inspectable: {:?}", path),
227 Some(x) => x,
228 }
229 }
230 }
231
232 macro_rules! finders {
233 ($(($name:ident, $get:ident, $iter:ident, $( $mutable:ident )? ))*) => {$(
234 impl<'obj, 'ser, 'pb, 'pbobj> Inspectable<'ser> {
235 fn $name(
236 &'obj $($mutable)? self,
237 steps: &'pbobj Path<'pb>,
238 pc: usize,
239 ) -> Option<&'obj $($mutable)? Inspectable<'ser>> {
240 let current_step = if let Some(x) = steps.get(pc) {
241 x
242 } else {
243 return Some(self);
244 };
245
246 let descend_into_entry =
247 |entry: &'obj $($mutable)? InDictEntry<'ser>| -> Option<&'obj $($mutable)? Inspectable<'ser>> {
248 match steps.get(pc + 1) {
249 Some(Step::Key) => entry.key.$name(steps, pc + 2),
250 Some(Step::Value) => entry.value.$name(steps, pc + 2),
251 _ => panic!(
252 "A path that selects a dict entry must then select either its key or its value"
253 ),
254 }
255 };
256
257 match (self, current_step) {
258 (Inspectable::Raw(_), _) => (),
259
260 (s @ Inspectable::Int(_), Step::Search(Search::Int(x))) => {
261 if *x == &*s.int_ref().bytes {
262 return Some(s);
263 }
264 },
265 (Inspectable::Int(_), _) => (),
266
267 (s @ Inspectable::String(_), Step::Search(Search::ByteString(x))) => {
268 if *x == &*s.string_ref().bytes {
269 return Some(s);
270 }
271 },
272 (Inspectable::String(_), Step::Search(_)) => (),
273 (Inspectable::String(_), _) => (),
274
275 (Inspectable::List(_), Step::Key) => (),
276 (Inspectable::List(_), Step::Value) => (),
277 (Inspectable::List(_), Step::Entry(_)) => (),
278 (Inspectable::List(in_list), Step::Nth(idx)) => {
279 let item = in_list.items.$get(*idx)?;
280 return item.$name(steps, pc + 1);
281 },
282 (Inspectable::List(in_list), Step::Search(_)) => {
283 return in_list
284 .items
285 .$iter()
286 .find_map(|item| item.$name(steps, pc));
287 },
288
289 (Inspectable::Dict(_), Step::Key) => (),
290 (Inspectable::Dict(_), Step::Value) => (),
291 (Inspectable::Dict(in_dict), Step::Nth(idx)) => {
292 let entry = in_dict.items.$get(*idx)?;
293 return descend_into_entry(entry);
294 },
295 (Inspectable::Dict(in_dict), Step::Entry(key)) => {
296 let entry = in_dict.items.$iter().find(|entry| {
297 let entry_key = if let Inspectable::String(x) = &entry.key {
298 x
299 } else {
300 return false;
301 };
302 entry_key.bytes == *key
303 })?;
304 return descend_into_entry(entry);
305 },
306 (Inspectable::Dict(in_dict), Step::Search(Search::DictKey(key))) => {
307 return in_dict.items.$iter().find_map(|entry| {
308 if let Inspectable::String(x) = &entry.key {
309 if x.bytes == *key {
310 return descend_into_entry(entry);
311 }
312 }
313 entry.value.$name(steps, pc)
314 });
315 },
316 (Inspectable::Dict(in_dict), Step::Search(_)) => {
317 return in_dict
318 .items
319 .$iter()
320 .find_map(|InDictEntry { value, .. }| value.$name(steps, pc));
321 },
322 };
323 None
324 }
325 }
326 )*};
327 }
328
329 finders!(
330 (find_impl, get_mut, iter_mut, mut)
331 (find_ref_impl, get, iter,)
332 );
333
334 macro_rules! variant_accessors {
335 ($(($name:ident, $mutname:ident, $source:ident, $target:ty, $targettype:ty))*) => {$(
336 impl<'obj, 'ser> Inspectable<'ser> {
337 #[doc=concat!("Coercion to immutable reference to [`", stringify!($targettype), "`]. Panics on failure.")]
338 pub fn $name(&'obj self) -> &'obj $target {
339 match self {
340 Inspectable::$source(x) => x,
341 _ => panic!("Attempted to take non-{} Inspectable as {}", stringify!($source), stringify!($target))
342 }
343 }
344 #[doc=concat!("Coercion to mutable reference to [`", stringify!($targettype), "`]. Panics on failure.")]
345 pub fn $mutname(&'obj mut self) -> &'obj mut $target {
346 match self {
347 Inspectable::$source(x) => x,
348 _ => panic!("Attempted to take non-{} Inspectable as mut_{}", stringify!($source), stringify!($target))
349 }
350 }
351 }
352 )*};
353 }
354
355 variant_accessors! {
356 (string_ref, string, String, InString<'ser>, InString)
357 (int_ref, int, Int, InInt<'ser>, InInt)
358 (raw_ref, raw, Raw, Cow<'ser, [u8]>, [u8])
359 (dict_ref, dict, Dict, InDict<'ser>, InDict)
360 (list_ref, list, List, InList<'ser>, InList)
361 }
362
363 impl<'obj, 'ser> InList<'ser> {
364 pub fn nth_ref(&'obj self, idx: usize) -> &'obj Inspectable<'ser> {
365 self.items
366 .get(idx)
367 .expect("Could not access nth Inspectable in list")
368 }
369
370 pub fn nth(&'obj mut self, idx: usize) -> &'obj mut Inspectable<'ser> {
371 self.items
372 .get_mut(idx)
373 .expect("Could not mutably access nth Inspectable in list")
374 }
375 }
376
377 impl<'obj, 'ser> InDict<'ser> {
378 pub fn nth_ref(&'obj self, idx: usize) -> &'obj InDictEntry<'ser> {
379 self.items
380 .get(idx)
381 .expect("Could not access nth Inspectable in list")
382 }
383
384 pub fn nth(&'obj mut self, idx: usize) -> &'obj mut InDictEntry<'ser> {
385 self.items
386 .get_mut(idx)
387 .expect("Could not mutably access nth Inspectable in list")
388 }
389 }
390
391 impl<'obj, 'ser, 'other> InDict<'ser> {
392 pub fn entry_ref(&'obj self, name: &'other [u8]) -> &'obj InDictEntry<'ser> {
393 self.items
394 .iter()
395 .find(|InDictEntry { key, .. }| key.string_ref().bytes == name)
396 .expect("Could not find a Dict Entry with requested key")
397 }
398
399 pub fn entry(&'obj mut self, name: &'other [u8]) -> &'obj mut InDictEntry<'ser> {
400 self.items
401 .iter_mut()
402 .find(|InDictEntry { key, .. }| key.string_ref().bytes == name)
403 .expect("Could not find a Dict Entry with requested key")
404 }
405 }