1use std::{
14 borrow::Cow,
15 fmt,
16};
17
18use toml_edit::{
19 Array,
20 Item,
21 Table,
22 Value,
23};
24
25#[derive(Debug, Clone)]
27pub struct Path {
28 components: Vec<PathComponent>,
29}
30
31impl fmt::Display for Path {
32 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33 for (i, c) in self.components.iter().enumerate() {
34 if i > 0 {
35 f.write_str(".")?;
36 }
37
38 write!(f, "{}", c)?;
39 }
40
41 Ok(())
42 }
43}
44
45impl std::str::FromStr for Path {
46 type Err = PathError;
47
48 fn from_str(s: &str) -> PathResult<Self> {
49 Ok(Path {
50 components: s.split(".").map(PathComponent::from_str)
51 .collect::<PathResult<Vec<_>>>()?,
52 })
53 }
54}
55
56impl Path {
57 pub fn len(&self) -> usize {
59 self.components.len()
60 }
61
62 pub fn is_empty(&self) -> bool {
64 self.components.is_empty()
65 }
66
67 pub fn empty() -> Path {
69 Path {
70 components: Vec::new(),
71 }
72 }
73
74 pub fn get(&self, idx: usize) -> Option<&PathComponent> {
76 self.components.get(idx)
77 }
78
79 pub fn iter(&self) -> impl Iterator<Item = &PathComponent> {
81 self.components.iter()
82 }
83
84 pub fn push(&mut self, component: PathComponent) {
86 self.components.push(component);
87 }
88
89 pub fn pop(&mut self) -> Option<PathComponent> {
91 self.components.pop()
92 }
93}
94
95#[derive(Debug, Clone)]
97pub enum PathComponent {
98 Symbol(String),
100
101 Index(usize),
103}
104
105impl fmt::Display for PathComponent {
106 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
107 match self {
108 PathComponent::Symbol(s) => write!(f, "{}", s),
109 PathComponent::Index(i) => write!(f, "{}", i),
110 }
111 }
112}
113
114impl From<usize> for PathComponent {
115 fn from(v: usize) -> Self {
116 PathComponent::Index(v)
117 }
118}
119
120impl From<&str> for PathComponent {
121 fn from(v: &str) -> Self {
122 PathComponent::Symbol(v.into())
123 }
124}
125
126impl std::str::FromStr for PathComponent {
127 type Err = PathError;
128
129 fn from_str(s: &str) -> PathResult<Self> {
130 if s.contains('.') {
131 return Err(PathError::InvalidPathComponent(
132 "must not contain a period (\".\")"));
133 }
134
135 if let Ok(i) = s.parse::<usize>() {
136 Ok(PathComponent::Index(i))
137 } else {
138 Ok(PathComponent::Symbol(s.into()))
139 }
140 }
141}
142
143impl PathComponent {
144 pub fn as_symbol(&self) -> Result<&str> {
146 match self {
147 PathComponent::Symbol(s) => Ok(s),
148 PathComponent::Index(i) => Err(Error::BadSymbol(*i)),
149 }
150 }
151
152 pub fn as_index(&self) -> Result<usize> {
154 match self {
155 PathComponent::Symbol(s) => Err(Error::BadIndex(s.to_string())),
156 PathComponent::Index(i) => Ok(*i),
157 }
158 }
159}
160
161pub type PathResult<T> = std::result::Result<T, PathError>;
163
164#[derive(thiserror::Error, Debug)]
166pub enum PathError {
167 #[error("invalid path component: {0}")]
168 InvalidPathComponent(&'static str),
169}
170
171pub trait Node: fmt::Debug {
173 fn type_name(&self) -> &'static str;
175
176 fn as_array(&self) -> Option<&Array>;
178
179 fn as_array_mut(&mut self) -> Option<&mut Array>;
181
182 fn as_atomic_value(&self) -> Option<&Value>;
184
185 fn as_table_mut(&mut self) -> Option<&mut Table>;
187
188 fn get(&self, key: &PathComponent) -> Result<&dyn Node>;
190
191 fn get_mut(&mut self, key: &PathComponent) -> Result<&mut dyn Node>;
193
194 fn set(&mut self, key: &PathComponent, value: Value) -> Result<()>;
196
197 fn remove(&mut self, key: &PathComponent) -> Result<()>;
199
200 fn iter<'i>(&'i self) -> Box<(dyn Iterator<Item = (PathComponent, &'i dyn Node)> + 'i)>;
202
203 fn traverse(&self, path: &Path) -> TraversalResult<&dyn Node>
206 where
207 Self: Sized,
208 {
209 let mut node: &dyn Node = self as _;
210 for (i, pc) in path.iter().cloned().enumerate() {
211 let type_name = node.type_name();
212 node = node.get(&pc)
213 .map_err(|e| e.with_context(path, i, type_name))?;
214 }
215
216 Ok(node)
217 }
218
219 fn traverse_mut(&mut self, path: &Path) -> TraversalResult<&mut dyn Node>
222 where
223 Self: Sized,
224 {
225 let mut node: &mut dyn Node = self as _;
226 for (i, pc) in path.iter().cloned().enumerate() {
227 let type_name = node.type_name();
228 node = node.get_mut(&pc)
229 .map_err(|e| e.with_context(path, i, type_name))?;
230 }
231
232 Ok(node)
233 }
234}
235
236impl Node for Item {
237 fn type_name(&self) -> &'static str {
238 self.type_name()
239 }
240
241 fn as_array(&self) -> Option<&Array> {
242 match self {
243 Item::Value(v) => v.as_array(),
244 | Item::None
245 | Item::Table(_)
246 | Item::ArrayOfTables(_) => None,
247 }
248 }
249
250 fn as_array_mut(&mut self) -> Option<&mut Array> {
251 match self {
252 Item::Value(v) => v.as_array_mut(),
253 | Item::None
254 | Item::Table(_)
255 | Item::ArrayOfTables(_) => None,
256 }
257 }
258
259 fn as_atomic_value(&self) -> Option<&Value> {
260 match self {
261 Item::Value(v) => v.as_atomic_value(),
262 | Item::None
263 | Item::Table(_)
264 | Item::ArrayOfTables(_) => None,
265 }
266 }
267
268 fn as_table_mut(&mut self) -> Option<&mut Table> {
269 match self {
270 Item::Table(t) => Some(t),
271 | Item::None
272 | Item::Value(_)
273 | Item::ArrayOfTables(_) => None,
274 }
275 }
276
277 fn get(&self, key: &PathComponent) -> Result<&dyn Node> {
278 match self {
279 Item::None => Err(Error::LookupError("none")),
280 Item::Value(v) => v.get(key),
281 Item::Table(t) => Node::get(t, key),
282 Item::ArrayOfTables(a) => {
283 let i = key.as_index()?;
284 Ok(a.get(i).ok_or_else(|| Error::OutOfBounds(i, a.len()))?)
285 },
286 }
287 }
288
289 fn get_mut(&mut self, key: &PathComponent) -> Result<&mut dyn Node> {
290 match self {
291 Item::None => Err(Error::LookupError("none")),
292 Item::Value(v) => v.get_mut(key),
293 Item::Table(t) => Node::get_mut(t, key),
294 Item::ArrayOfTables(a) => {
295 let i = key.as_index()?;
296 let l = a.len();
297 Ok(a.get_mut(i).ok_or_else(|| Error::OutOfBounds(i, l))?)
298 },
299 }
300 }
301
302 fn set(&mut self, key: &PathComponent, value: Value) -> Result<()> {
303 match self {
304 Item::None => Err(Error::InsertionError("none")),
305 Item::Value(v) => v.set(key, value),
306 Item::Table(t) => {
307 t.insert(key.as_symbol()?, Item::Value(value));
308 Ok(())
309 },
310 Item::ArrayOfTables(_) => {
311 Err(Error::InsertionError(self.type_name()))
313 },
314 }
315 }
316
317 fn remove(&mut self, key: &PathComponent) -> Result<()> {
318 match self {
319 Item::None => Err(Error::RemovalError("none")),
320 Item::Value(v) => v.remove(key),
321 Item::Table(t) => {
322 let s = key.as_symbol()?;
323 t.remove(s).ok_or(Error::KeyNotFound(s.into()))?;
324 Ok(())
325 },
326 Item::ArrayOfTables(a) => {
327 let i = key.as_index()?;
328 let l = a.len();
329 if i >= l {
330 return Err(Error::OutOfBounds(i, l));
331 }
332 a.remove(i);
333 Ok(())
334 },
335 }
336 }
337
338 fn iter<'i>(&'i self) -> Box<(dyn Iterator<Item = (PathComponent, &'i dyn Node)> + 'i)> {
339 match self {
340 Item::None => Box::new(std::iter::empty()),
341 Item::Value(v) => v.iter(),
342 Item::Table(t) => Node::iter(t),
343 Item::ArrayOfTables(a) =>
344 Box::new(a.iter().enumerate().map(|(k, v)| (k.into(), &*v as &dyn Node))),
345 }
346 }
347}
348
349impl Node for Table {
350 fn type_name(&self) -> &'static str {
351 "table"
352 }
353
354 fn as_array(&self) -> Option<&Array> {
355 None
356 }
357
358 fn as_array_mut(&mut self) -> Option<&mut Array> {
359 None
360 }
361
362 fn as_atomic_value(&self) -> Option<&Value> {
363 None
364 }
365
366 fn as_table_mut(&mut self) -> Option<&mut Table> {
367 Some(self)
368 }
369
370 fn get(&self, key: &PathComponent) -> Result<&dyn Node> {
371 let s = key.as_symbol()?;
372 Ok(self.get(s).ok_or_else(|| Error::KeyNotFound(s.into()))?)
373 }
374
375 fn get_mut(&mut self, key: &PathComponent) -> Result<&mut dyn Node> {
376 let s = key.as_symbol()?;
377 Ok(self.get_mut(s).ok_or_else(|| Error::KeyNotFound(s.into()))?)
378 }
379
380 fn set(&mut self, key: &PathComponent, value: Value) -> Result<()> {
381 let s = key.as_symbol()?;
382 self.insert(s, Item::Value(value));
383 Ok(())
384 }
385
386 fn remove(&mut self, key: &PathComponent) -> Result<()> {
387 let s = key.as_symbol()?;
388 self.remove(s).ok_or(Error::KeyNotFound(s.into()))?;
389 Ok(())
390 }
391
392 fn iter<'i>(&'i self) -> Box<(dyn Iterator<Item = (PathComponent, &'i dyn Node)> + 'i)> {
393 Box::new(self.iter().map(|(k, v)| (k.into(), &*v as &dyn Node)))
394 }
395}
396
397impl Node for Value {
398 fn type_name(&self) -> &'static str {
399 self.type_name()
400 }
401
402 fn as_array(&self) -> Option<&Array> {
403 match self {
404 Value::Array(a) => Some(a),
405 | Value::String(_)
406 | Value::Integer(_)
407 | Value::Float(_)
408 | Value::Boolean(_)
409 | Value::Datetime(_)
410 | Value::InlineTable(_) =>
411 None,
412 }
413 }
414
415 fn as_array_mut(&mut self) -> Option<&mut Array> {
416 match self {
417 Value::Array(a) => Some(a),
418 | Value::String(_)
419 | Value::Integer(_)
420 | Value::Float(_)
421 | Value::Boolean(_)
422 | Value::Datetime(_)
423 | Value::InlineTable(_) =>
424 None,
425 }
426 }
427
428 fn as_atomic_value(&self) -> Option<&Value> {
429 match self {
430 | Value::String(_)
431 | Value::Integer(_)
432 | Value::Float(_)
433 | Value::Boolean(_)
434 | Value::Datetime(_) =>
435 Some(self),
436 | Value::Array(_)
437 | Value::InlineTable(_) =>
438 None,
439 }
440 }
441
442 fn as_table_mut(&mut self) -> Option<&mut Table> {
443 None
444 }
445
446 fn get(&self, key: &PathComponent) -> Result<&dyn Node> {
447 match self {
448 | Value::String(_)
449 | Value::Integer(_)
450 | Value::Float(_)
451 | Value::Boolean(_)
452 | Value::Datetime(_) =>
453 Err(Error::LookupError(self.type_name())),
454 Value::Array(a) => {
455 let i = key.as_index()?;
456 Ok(a.get(i).ok_or_else(|| Error::OutOfBounds(i, a.len()))?)
457 },
458 Value::InlineTable(t) => {
459 let s = key.as_symbol()?;
460 Ok(t.get(s).ok_or_else(|| Error::KeyNotFound(s.into()))?)
461 },
462 }
463 }
464
465 fn get_mut(&mut self, key: &PathComponent) -> Result<&mut dyn Node> {
466 match self {
467 | Value::String(_)
468 | Value::Integer(_)
469 | Value::Float(_)
470 | Value::Boolean(_)
471 | Value::Datetime(_) =>
472 Err(Error::LookupError(self.type_name())),
473 Value::Array(a) => {
474 let i = key.as_index()?;
475 let l = a.len();
476 Ok(a.get_mut(i).ok_or_else(|| Error::OutOfBounds(i, l))?)
477 },
478 Value::InlineTable(t) => {
479 let s = key.as_symbol()?;
480 Ok(t.get_mut(s).ok_or_else(|| Error::KeyNotFound(s.into()))?)
481 },
482 }
483 }
484
485 fn set(&mut self, key: &PathComponent, value: Value) -> Result<()> {
486 match self {
487 | Value::String(_)
488 | Value::Integer(_)
489 | Value::Float(_)
490 | Value::Boolean(_)
491 | Value::Datetime(_) =>
492 Err(Error::InsertionError(self.type_name())),
493 Value::Array(a) => {
494 let i = key.as_index()?;
495 let l = a.len();
496 if i >= l {
497 return Err(Error::OutOfBounds(i, l));
498 }
499 a.replace(i, value);
500 Ok(())
501 },
502 Value::InlineTable(t) => {
503 t.insert(key.as_symbol()?, value);
504 Ok(())
505 },
506 }
507 }
508
509 fn remove(&mut self, key: &PathComponent) -> Result<()> {
510 match self {
511 | Value::String(_)
512 | Value::Integer(_)
513 | Value::Float(_)
514 | Value::Boolean(_)
515 | Value::Datetime(_) =>
516 Err(Error::RemovalError(self.type_name())),
517 Value::Array(a) => {
518 let i = key.as_index()?;
519 let l = a.len();
520 if i >= l {
521 return Err(Error::OutOfBounds(i, l));
522 }
523 a.remove(i);
524 Ok(())
525 },
526 Value::InlineTable(t) => {
527 let s = key.as_symbol()?;
528 t.remove(s).ok_or(Error::KeyNotFound(s.into()))?;
529 Ok(())
530 },
531 }
532 }
533
534 fn iter<'i>(&'i self) -> Box<(dyn Iterator<Item = (PathComponent, &'i dyn Node)> + 'i)> {
535 match self {
536 | Value::String(_)
537 | Value::Integer(_)
538 | Value::Float(_)
539 | Value::Boolean(_)
540 | Value::Datetime(_) =>
541 Box::new(std::iter::empty()),
542 Value::Array(a) =>
543 Box::new(a.iter().enumerate().map(|(k, v)| (k.into(), &*v as &dyn Node))),
544 Value::InlineTable(t) =>
545 Box::new(t.iter().map(|(k, v)| (k.into(), &*v as &dyn Node))),
546 }
547 }
548}
549
550pub type Result<T> = std::result::Result<T, Error>;
552
553#[derive(thiserror::Error, Debug)]
555pub enum Error {
556 #[error("key {0:?} not found")]
557 KeyNotFound(String),
558
559 #[error("index {0} is out of bounds")]
560 OutOfBounds(usize, usize),
561
562 #[error("cannot index into a {0}")]
563 LookupError(&'static str),
564
565 #[error("cannot insert into a {0}")]
566 InsertionError(&'static str),
567
568 #[error("cannot remove items from a {0}")]
569 RemovalError(&'static str),
570
571 #[error("{0:?} is not a numeric index")]
572 BadIndex(String),
573
574 #[error("{0:?} is not a valid symbol")]
575 BadSymbol(usize),
576}
577
578impl Error {
579 pub fn with_context(self, path: &Path, i: usize, type_name: &'static str)
581 -> TraversalError
582 {
583 let p = Path {
584 components: path.components[..i].iter().cloned().collect(),
585 };
586 match self {
587 Error::KeyNotFound(k) => TraversalError::KeyNotFound(p, k),
588 Error::OutOfBounds(i, l) => TraversalError::OutOfBounds(p, i, l),
589 Error::LookupError(t) => match &path.components[i] {
590 PathComponent::Symbol(s) =>
591 TraversalError::KeyLookupBadType(p, s.into(), t),
592 PathComponent::Index(i) =>
593 TraversalError::IndexLookupBadType(p, *i, t)
594 },
595 Error::BadIndex(s) =>
596 TraversalError::KeyLookupBadType(p, s, type_name),
597 Error::BadSymbol(i) =>
598 TraversalError::IndexLookupBadType(p, i, type_name),
599 Error::InsertionError(_) | Error::RemovalError(_) =>
600 unreachable!("not applicable for traversals"),
601 }
602 }
603}
604
605pub type TraversalResult<T> = std::result::Result<T, TraversalError>;
607
608#[derive(thiserror::Error, Debug)]
610pub enum TraversalError {
611 #[error("Tried to look up {1:?}{path}, \
612 but it does not exist",
613 path=Self::fmt_path("in", &.0))]
614 KeyNotFound(Path, String),
615
616 #[error("Tried to get the item at index {1}{path}, \
617 but there are only {2} items",
618 path=Self::fmt_path("from", &.0))]
619 OutOfBounds(Path, usize, usize),
620
621 #[error("Tried to look up {1:?}{path}, \
622 but the latter is a {2}, not a table",
623 path=Self::fmt_path("in", &.0))]
624 KeyLookupBadType(Path, String, &'static str),
625
626 #[error("Tried to get the item at index {1}{path}, \
627 but the latter is a {2}, not an array",
628 path=Self::fmt_path("from", &.0))]
629 IndexLookupBadType(Path, usize, &'static str),
630}
631
632impl TraversalError {
633 fn fmt_path(preposition: &'static str, p: &Path) -> Cow<'static, str> {
636 if p.is_empty() {
637 "".into()
638 } else {
639 format!(" {} {}", preposition, p).into()
640 }
641 }
642}