Skip to main content

cimview/
index.rs

1//! Where things are written in an RDF/XML document.
2//!
3//! The decoder keeps no positions — it is the hot path, and nothing else
4//! needs them — so an editor makes its own pass with quick-xml over each
5//! document it shows. The index records, as [`Range`]s, every top-level
6//! element (an object), its `rdf:ID` / `rdf:about`, its field elements and
7//! their `rdf:resource` targets. mRIDs follow the decoder: the text after the
8//! last `#`.
9//!
10//! A document being edited is often not well-formed; the pass stops at the
11//! first syntax error and keeps what it has.
12
13use cimmodel::base::ClassDef;
14use cimmodel::registry::type_registry;
15use quick_xml::Reader;
16use quick_xml::events::Event;
17
18use crate::mrid_of;
19pub use crate::text::{LineIndex, Position, Range, contains};
20
21/// `rdf:ID` defines an object; `rdf:about` describes one defined elsewhere.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum IdKind {
24    Id,
25    About,
26}
27
28#[derive(Debug)]
29pub struct Element {
30    /// The tag as written, e.g. `cim:ACLineSegment`.
31    pub qname: String,
32    pub mrid: String,
33    pub id_kind: Option<IdKind>,
34    /// The start tag.
35    pub head: Range,
36    /// The value of `rdf:ID` / `rdf:about`, without quotes.
37    pub id_range: Option<Range>,
38    /// Start tag to end tag.
39    pub full: Range,
40    pub fields: Vec<Field>,
41    /// `IdentifiedObject.name`, for labels.
42    pub name: Option<String>,
43}
44
45#[derive(Debug)]
46pub struct Field {
47    /// The tag as written, e.g. `cim:ACLineSegment.r`.
48    pub qname: String,
49    /// The start tag.
50    pub head: Range,
51    /// Start tag to end tag.
52    pub full: Range,
53    /// The `rdf:resource` target as an mRID, and the range of its value.
54    pub resource: Option<(String, Range)>,
55}
56
57impl Field {
58    /// The field key the decoder stores this field under: the local name.
59    pub fn key(&self) -> &str {
60        local(&self.qname)
61    }
62}
63
64#[derive(Debug, Default)]
65pub struct Index {
66    /// `xmlns` bindings of the root element: (prefix, IRI); `""` for the
67    /// default namespace.
68    pub namespaces: Vec<(String, String)>,
69    pub elements: Vec<Element>,
70}
71
72/// The local part of a qualified name.
73pub fn local(qname: &str) -> &str {
74    qname.rsplit_once(':').map_or(qname, |(_, l)| l)
75}
76
77/// The prefix of a qualified name, `""` when it has none.
78pub fn prefix(qname: &str) -> &str {
79    qname.split_once(':').map_or("", |(p, _)| p)
80}
81
82impl Index {
83    pub fn build(text: &str) -> Self {
84        let lines = LineIndex::new(text);
85        let mut ix = Index::default();
86        let mut reader = Reader::from_str(text);
87        reader.config_mut().check_end_names = false;
88
89        let mut depth = 0u32;
90        let mut current: Option<Element> = None;
91        let mut field: Option<Field> = None;
92        let mut name_text: Option<String> = None;
93        loop {
94            let start = reader.buffer_position() as usize;
95            let event = match reader.read_event() {
96                Ok(Event::Eof) | Err(_) => break,
97                Ok(e) => e,
98            };
99            let end = reader.buffer_position() as usize;
100            let range = || lines.range(text, start, end);
101            let empty = matches!(event, Event::Empty(_));
102            match event {
103                Event::Start(e) | Event::Empty(e) if depth == 0 => {
104                    // The root: keep its namespace bindings.
105                    for a in e.attributes().flatten() {
106                        let key = String::from_utf8_lossy(a.key.as_ref());
107                        let prefix = if key == "xmlns" { Some("") } else { key.strip_prefix("xmlns:") };
108                        if let Some(p) = prefix {
109                            ix.namespaces.push((p.to_string(), String::from_utf8_lossy(&a.value).into_owned()));
110                        }
111                    }
112                    if !empty {
113                        depth = 1;
114                    }
115                }
116                Event::Start(e) | Event::Empty(e) if depth == 1 => {
117                    let tag = &text[start..end];
118                    let (id_kind, id_range, mrid) = match attr_value(tag, "rdf:ID")
119                        .map(|s| (IdKind::Id, s))
120                        .or_else(|| attr_value(tag, "rdf:about").map(|s| (IdKind::About, s)))
121                    {
122                        Some((kind, (vs, ve))) => (
123                            Some(kind),
124                            Some(lines.range(text, start + vs, start + ve)),
125                            mrid_of(&tag[vs..ve]).to_string(),
126                        ),
127                        None => (None, None, String::new()),
128                    };
129                    let el = Element {
130                        qname: String::from_utf8_lossy(e.name().as_ref()).into_owned(),
131                        mrid,
132                        id_kind,
133                        head: range(),
134                        id_range,
135                        full: range(),
136                        fields: Vec::new(),
137                        name: None,
138                    };
139                    if !empty {
140                        current = Some(el);
141                        depth = 2;
142                    } else {
143                        ix.elements.push(el);
144                    }
145                }
146                Event::Start(e) | Event::Empty(e) if depth == 2 => {
147                    let tag = &text[start..end];
148                    let resource = attr_value(tag, "rdf:resource").map(|(vs, ve)| {
149                        (mrid_of(&tag[vs..ve]).to_string(), lines.range(text, start + vs, start + ve))
150                    });
151                    let f = Field {
152                        qname: String::from_utf8_lossy(e.name().as_ref()).into_owned(),
153                        head: range(),
154                        full: range(),
155                        resource,
156                    };
157                    if let Some(el) = current.as_mut() {
158                        if !empty {
159                            name_text = (f.key() == "IdentifiedObject.name").then(String::new);
160                            field = Some(f);
161                        } else {
162                            el.fields.push(f);
163                        }
164                    }
165                    if !empty {
166                        depth = 3;
167                    }
168                }
169                Event::Start(_) => depth += 1,
170                Event::Text(t) if depth == 3 => {
171                    if let Some(name) = name_text.as_mut() {
172                        name.push_str(&t.unescape().unwrap_or_default());
173                    }
174                }
175                Event::CData(t) if depth == 3 => {
176                    if let Some(name) = name_text.as_mut() {
177                        name.push_str(&String::from_utf8_lossy(&t));
178                    }
179                }
180                Event::End(_) => {
181                    depth = depth.saturating_sub(1);
182                    match depth {
183                        2 => {
184                            if let (Some(el), Some(mut f)) = (current.as_mut(), field.take()) {
185                                f.full.end = range().end;
186                                if let Some(name) = name_text.take() {
187                                    el.name = Some(name.trim().to_string());
188                                }
189                                // A bare `<` being typed parses as a nameless tag.
190                                if !f.qname.is_empty() {
191                                    el.fields.push(f);
192                                }
193                            }
194                        }
195                        1 => {
196                            if let Some(mut el) = current.take() {
197                                el.full.end = range().end;
198                                ix.elements.push(el);
199                            }
200                        }
201                        _ => {}
202                    }
203                }
204                _ => {}
205            }
206        }
207        // A document cut short — or with a tag left half-typed, which
208        // swallows what follows — keeps its open element, to the end.
209        if let Some(mut el) = current {
210            el.full.end = lines.position(text, text.len());
211            if let Some(f) = field.filter(|f| !f.qname.is_empty()) {
212                el.fields.push(f);
213            }
214            ix.elements.push(el);
215        }
216        ix
217    }
218
219    /// The namespace IRI `prefix` is bound to at the root.
220    pub fn namespace(&self, prefix: &str) -> Option<&str> {
221        self.namespaces.iter().find(|(p, _)| p == prefix).map(|(_, ns)| ns.as_str())
222    }
223
224    /// The prefix bound to `ns` at the root.
225    pub fn prefix_of(&self, ns: &str) -> Option<&str> {
226        self.namespaces.iter().find(|(_, n)| n == ns).map(|(p, _)| p.as_str())
227    }
228
229    /// The class of an element written `qname` here: by its prefix's namespace, else by its
230    /// local name alone.
231    pub fn class_of(&self, qname: &str) -> Option<&'static ClassDef> {
232        let reg = type_registry();
233        self.namespace(prefix(qname))
234            .and_then(|ns| reg.ns_table(ns))
235            .and_then(|t| t.get(local(qname)).copied())
236            .or_else(|| reg.bare().get(local(qname)).copied())
237    }
238
239    /// The element whose start-to-end span contains `pos`.
240    pub fn element_at(&self, pos: Position) -> Option<&Element> {
241        // Elements are in document order and do not overlap.
242        let i = self.elements.partition_point(|e| e.full.end < pos);
243        self.elements.get(i).filter(|e| contains(e.full, pos))
244    }
245}
246
247/// The byte span of attribute `name`'s value within a start tag, without its
248/// quotes.
249fn attr_value(tag: &str, name: &str) -> Option<(usize, usize)> {
250    let bytes = tag.as_bytes();
251    let mut from = 0;
252    while let Some(i) = tag[from..].find(name).map(|i| i + from) {
253        from = i + name.len();
254        // A whole attribute name: preceded by whitespace, followed by `=`.
255        if i == 0 || !bytes[i - 1].is_ascii_whitespace() {
256            continue;
257        }
258        let rest = tag[from..].trim_start();
259        let Some(rest) = rest.strip_prefix('=') else { continue };
260        let rest = rest.trim_start();
261        let quote = rest.chars().next()?;
262        if quote != '"' && quote != '\'' {
263            continue;
264        }
265        let vs = tag.len() - rest.len() + 1;
266        let ve = vs + tag[vs..].find(quote)?;
267        return Some((vs, ve));
268    }
269    None
270}
271
272#[cfg(test)]
273mod tests {
274    use super::*;
275
276    const DOC: &str = r##"<?xml version="1.0" encoding="UTF-8"?>
277<rdf:RDF xmlns:cim="http://iec.ch/TC57/CIM100#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
278  <cim:ACLineSegment rdf:ID="_line">
279    <cim:IdentifiedObject.name>Line &amp; 1</cim:IdentifiedObject.name>
280    <cim:ACLineSegment.r>0.5</cim:ACLineSegment.r>
281    <cim:ConductingEquipment.BaseVoltage rdf:resource="#_bv"/>
282  </cim:ACLineSegment>
283  <cim:BaseVoltage
284      rdf:about="urn:uuid:x#_bv" />
285</rdf:RDF>
286"##;
287
288    fn pos(line: u32, character: u32) -> Position {
289        Position { line, character }
290    }
291
292    #[test]
293    fn indexes_elements_fields_and_references() {
294        let ix = Index::build(DOC);
295        assert_eq!(ix.namespace("cim"), Some("http://iec.ch/TC57/CIM100#"));
296        assert_eq!(ix.elements.len(), 2);
297
298        let line = &ix.elements[0];
299        assert_eq!((line.qname.as_str(), line.mrid.as_str(), line.id_kind), ("cim:ACLineSegment", "_line", Some(IdKind::Id)));
300        assert_eq!(line.id_range, Some(Range { start: pos(2, 29), end: pos(2, 34) }));
301        assert_eq!(line.full.start, pos(2, 2));
302        assert_eq!(line.full.end, pos(6, 22));
303        assert_eq!(line.name.as_deref(), Some("Line & 1"));
304        let keys: Vec<&str> = line.fields.iter().map(Field::key).collect();
305        assert_eq!(keys, ["IdentifiedObject.name", "ACLineSegment.r", "ConductingEquipment.BaseVoltage"]);
306        assert_eq!(line.fields[1].full, Range { start: pos(4, 4), end: pos(4, 50) });
307        let (target, at) = line.fields[2].resource.clone().unwrap();
308        assert_eq!(target, "_bv");
309        assert_eq!(at, Range { start: pos(5, 55), end: pos(5, 59) });
310
311        let bv = &ix.elements[1];
312        assert_eq!((bv.mrid.as_str(), bv.id_kind), ("_bv", Some(IdKind::About)));
313        assert_eq!(bv.head, Range { start: pos(7, 2), end: pos(8, 35) });
314
315        assert_eq!(ix.element_at(pos(4, 10)).map(|e| e.mrid.as_str()), Some("_line"));
316        assert!(ix.element_at(pos(1, 3)).is_none());
317    }
318
319    #[test]
320    fn a_truncated_document_keeps_what_it_has() {
321        let cut = &DOC[..DOC.find("<cim:ACLineSegment.r>").unwrap() + 25];
322        let ix = Index::build(cut);
323        assert_eq!(ix.elements.len(), 1);
324        assert_eq!(ix.elements[0].mrid, "_line");
325        assert_eq!(ix.elements[0].full.end, LineIndex::new(cut).position(cut, cut.len()));
326    }
327}