Skip to main content

adk_graph/definition/
location.rs

1//! Where each value of a YAML workflow sits, so a validation issue names its line and column.
2
3use std::collections::HashMap;
4
5use serde::Deserialize;
6use serde::de::{self, Deserializer, IgnoredAny, MapAccess, SeqAccess, Visitor};
7use serde_saphyr::Spanned;
8
9/// A 1-based line and column in a workflow file.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub struct SourceLocation {
12    /// The line, from 1.
13    pub line: u32,
14    /// The column, from 1.
15    pub column: u32,
16}
17
18impl std::fmt::Display for SourceLocation {
19    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
20        write!(f, "{}:{}", self.line, self.column)
21    }
22}
23
24/// The location of every value of a YAML document, keyed by its path (`edges[2].to`).
25#[derive(Debug, Default)]
26pub(crate) struct LocationIndex {
27    paths: HashMap<String, SourceLocation>,
28}
29
30impl LocationIndex {
31    /// Indexes `yaml`. A document that does not parse yields an empty index; the typed parse
32    /// reports why.
33    pub(crate) fn of_yaml(yaml: &str) -> Self {
34        let mut index = Self::default();
35        if let Ok(root) = serde_saphyr::from_str::<Spanned<Tree>>(yaml) {
36            index.add(String::new(), &root);
37        }
38        index
39    }
40
41    fn add(&mut self, path: String, node: &Spanned<Tree>) {
42        let location = &node.referenced;
43        if location.line() > 0 {
44            self.paths.insert(
45                path.clone(),
46                SourceLocation { line: location.line() as u32, column: location.column() as u32 },
47            );
48        }
49        match &node.value {
50            Tree::Map(entries) => {
51                for (key, value) in entries {
52                    let child = if path.is_empty() { key.clone() } else { format!("{path}.{key}") };
53                    self.add(child, value);
54                }
55            }
56            Tree::Seq(items) => {
57                for (index, item) in items.iter().enumerate() {
58                    self.add(format!("{path}[{index}]"), item);
59                }
60            }
61            Tree::Scalar => {}
62        }
63    }
64
65    /// The location of `path`, or of its nearest indexed ancestor.
66    pub(crate) fn locate(&self, path: &str) -> Option<SourceLocation> {
67        let mut path = path;
68        loop {
69            if let Some(location) = self.paths.get(path) {
70                return Some(*location);
71            }
72            let cut = path.rfind(['.', '['])?;
73            path = &path[..cut];
74        }
75    }
76}
77
78/// A YAML value's shape, with the location of each child.
79enum Tree {
80    Map(Vec<(String, Spanned<Tree>)>),
81    Seq(Vec<Spanned<Tree>>),
82    Scalar,
83}
84
85impl<'de> Deserialize<'de> for Tree {
86    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
87        deserializer.deserialize_any(TreeVisitor)
88    }
89}
90
91struct TreeVisitor;
92
93impl<'de> Visitor<'de> for TreeVisitor {
94    type Value = Tree;
95
96    fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97        f.write_str("any YAML value")
98    }
99
100    fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Tree, A::Error> {
101        let mut entries = Vec::new();
102        while let Some(key) = map.next_key::<Key>()? {
103            entries.push((key.0, map.next_value::<Spanned<Tree>>()?));
104        }
105        Ok(Tree::Map(entries))
106    }
107
108    fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Tree, A::Error> {
109        let mut items = Vec::new();
110        while let Some(item) = seq.next_element::<Spanned<Tree>>()? {
111            items.push(item);
112        }
113        Ok(Tree::Seq(items))
114    }
115
116    fn visit_bool<E: de::Error>(self, _: bool) -> Result<Tree, E> {
117        Ok(Tree::Scalar)
118    }
119
120    fn visit_i64<E: de::Error>(self, _: i64) -> Result<Tree, E> {
121        Ok(Tree::Scalar)
122    }
123
124    fn visit_u64<E: de::Error>(self, _: u64) -> Result<Tree, E> {
125        Ok(Tree::Scalar)
126    }
127
128    fn visit_f64<E: de::Error>(self, _: f64) -> Result<Tree, E> {
129        Ok(Tree::Scalar)
130    }
131
132    fn visit_str<E: de::Error>(self, _: &str) -> Result<Tree, E> {
133        Ok(Tree::Scalar)
134    }
135
136    fn visit_unit<E: de::Error>(self) -> Result<Tree, E> {
137        Ok(Tree::Scalar)
138    }
139
140    fn visit_none<E: de::Error>(self) -> Result<Tree, E> {
141        Ok(Tree::Scalar)
142    }
143
144    fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<Tree, D::Error> {
145        deserializer.deserialize_any(TreeVisitor)
146    }
147}
148
149/// A mapping key as text, whatever scalar it is written as.
150struct Key(String);
151
152impl<'de> Deserialize<'de> for Key {
153    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
154        struct KeyVisitor;
155
156        impl<'de> Visitor<'de> for KeyVisitor {
157            type Value = Key;
158
159            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
160                f.write_str("a mapping key")
161            }
162
163            fn visit_str<E: de::Error>(self, value: &str) -> Result<Key, E> {
164                Ok(Key(value.to_string()))
165            }
166
167            fn visit_bool<E: de::Error>(self, value: bool) -> Result<Key, E> {
168                Ok(Key(value.to_string()))
169            }
170
171            fn visit_i64<E: de::Error>(self, value: i64) -> Result<Key, E> {
172                Ok(Key(value.to_string()))
173            }
174
175            fn visit_u64<E: de::Error>(self, value: u64) -> Result<Key, E> {
176                Ok(Key(value.to_string()))
177            }
178
179            fn visit_f64<E: de::Error>(self, value: f64) -> Result<Key, E> {
180                Ok(Key(value.to_string()))
181            }
182
183            fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Key, A::Error> {
184                while map.next_entry::<IgnoredAny, IgnoredAny>()?.is_some() {}
185                Ok(Key(String::new()))
186            }
187
188            fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Key, A::Error> {
189                while seq.next_element::<IgnoredAny>()?.is_some() {}
190                Ok(Key(String::new()))
191            }
192        }
193
194        deserializer.deserialize_any(KeyVisitor)
195    }
196}
197
198#[cfg(test)]
199mod tests {
200    use super::*;
201
202    #[test]
203    fn every_value_is_located_by_its_path() {
204        let index = LocationIndex::of_yaml(
205            "name: demo\nnodes:\n  a:\n    set: { x: 1 }\nedges:\n  - [START, a]\n  - from: a\n    to: END\n",
206        );
207        assert_eq!(index.locate("name"), Some(SourceLocation { line: 1, column: 7 }));
208        assert_eq!(index.locate("nodes.a.set.x"), Some(SourceLocation { line: 4, column: 15 }));
209        assert_eq!(index.locate("edges[0][1]"), Some(SourceLocation { line: 6, column: 13 }));
210        assert_eq!(index.locate("edges[1].to"), Some(SourceLocation { line: 8, column: 9 }));
211        // A missing key is reported at its nearest ancestor.
212        assert_eq!(index.locate("edges[1].routes[0]"), index.locate("edges[1]"));
213    }
214}