1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
use std::borrow::Cow;
use crate::linkedlist::{ LinkedList };
#[derive(Clone, Default, Debug)]
pub struct Context {
path: LinkedList<Location>
}
impl Context {
pub fn new() -> Context {
Default::default()
}
pub fn at(&self, loc: Location) -> Context {
let path = self.path.clone().push(loc);
Context { path }
}
pub fn path(&self) -> Path<'_> {
Path(Cow::Borrowed(&self.path))
}
}
pub struct Path<'a>(Cow<'a, LinkedList<Location>>);
impl <'a> Path<'a> {
pub fn to_owned(self) -> Path<'static> {
Path(Cow::Owned(self.0.into_owned()))
}
pub fn locations(&self) -> impl Iterator<Item = &Location> {
self.0.iter_back()
}
}
impl <'a> std::fmt::Display for Path<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut items = Vec::with_capacity(self.0.len());
for item in self.0.iter_back() {
items.push(item);
}
for (idx, loc) in items.iter().rev().enumerate() {
if idx != 0 {
f.write_str(".")?;
}
match &loc.inner {
Loc::Field(name) => f.write_str(&*name)?,
Loc::Index(i) => write!(f, "[{i}]")?,
Loc::Variant(name) => write!(f, "({name})")?
}
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Location {
inner: Loc
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Loc {
Field(Cow<'static, str>),
Index(usize),
Variant(Cow<'static, str>)
}
impl Location {
pub fn field(name: impl Into<Cow<'static,str>>) -> Self {
Location {
inner: Loc::Field(name.into())
}
}
pub fn variant(name: impl Into<Cow<'static,str>>) -> Self {
Location {
inner: Loc::Variant(name.into())
}
}
pub fn idx(i: usize) -> Self {
Location {
inner: Loc::Index(i)
}
}
}