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 std::sync::OnceLock;
14
15use cimmodel::base::{ClassDef, FastMap};
16use cimmodel::registry::type_registry;
17use quick_xml::Reader;
18use quick_xml::events::Event;
19
20use crate::mrid_of;
21pub use crate::text::{LineIndex, Position, Range, TextEdit, contains};
22
23/// `rdf:ID` defines an object; `rdf:about` describes one defined elsewhere.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum IdKind {
26    Id,
27    About,
28}
29
30#[derive(Debug)]
31pub struct Element {
32    /// The tag as written, e.g. `cim:ACLineSegment`.
33    pub qname: String,
34    pub mrid: String,
35    pub id_kind: Option<IdKind>,
36    /// The start tag.
37    pub head: Range,
38    /// The value of `rdf:ID` / `rdf:about`, without quotes.
39    pub id_range: Option<Range>,
40    /// Start tag to end tag.
41    pub full: Range,
42    pub fields: Vec<Field>,
43    /// `IdentifiedObject.name`, for labels.
44    pub name: Option<String>,
45}
46
47impl Element {
48    /// Moved down by `lines` (up, if negative), as text inserted above it moves it.
49    fn shift(&mut self, lines: i64) {
50        if lines == 0 {
51            return;
52        }
53        let mut ranges: Vec<&mut Range> = vec![&mut self.head, &mut self.full];
54        ranges.extend(self.id_range.as_mut());
55        for f in &mut self.fields {
56            ranges.push(&mut f.head);
57            ranges.push(&mut f.full);
58            ranges.extend(f.resource.as_mut().map(|(_, r)| r));
59        }
60        for r in ranges {
61            for p in [&mut r.start, &mut r.end] {
62                p.line = (p.line as i64 + lines) as u32;
63            }
64        }
65    }
66}
67
68#[derive(Debug)]
69pub struct Field {
70    /// The tag as written, e.g. `cim:ACLineSegment.r`.
71    pub qname: String,
72    /// The start tag.
73    pub head: Range,
74    /// Start tag to end tag.
75    pub full: Range,
76    /// The `rdf:resource` target as an mRID, and the range of its value.
77    pub resource: Option<(String, Range)>,
78}
79
80impl Field {
81    /// The field key the decoder stores this field under: the local name.
82    pub fn key(&self) -> &str {
83        local(&self.qname)
84    }
85}
86
87#[derive(Debug, Default)]
88pub struct Index {
89    /// `xmlns` bindings of the root element: (prefix, IRI); `""` for the
90    /// default namespace.
91    pub namespaces: Vec<(String, String)>,
92    pub elements: Vec<Element>,
93    /// The elements by mRID, by their place in `elements`: made on the first
94    /// [`Index::of`].
95    by_mrid: OnceLock<FastMap<String, Vec<u32>>>,
96}
97
98/// The local part of a qualified name.
99pub fn local(qname: &str) -> &str {
100    qname.rsplit_once(':').map_or(qname, |(_, l)| l)
101}
102
103/// The prefix of a qualified name, `""` when it has none.
104pub fn prefix(qname: &str) -> &str {
105    qname.split_once(':').map_or("", |(p, _)| p)
106}
107
108impl Index {
109    pub fn build(text: &str) -> Self {
110        let mut ix = Index::default();
111        scan(text, &LineIndex::new(text), 0..text.len(), &mut ix);
112        ix
113    }
114}
115
116/// The elements written in `text[within]` added to `ix`, their places those in `text` (whose lines
117/// are `lines`). From the start of `text`, the root's namespaces too; elsewhere, `within` holds
118/// whole objects. Whether it ended inside an element: cut short.
119fn scan(text: &str, lines: &LineIndex, within: std::ops::Range<usize>, ix: &mut Index) -> bool {
120    {
121        let from = within.start;
122        let mut reader = Reader::from_str(&text[within.clone()]);
123        reader.config_mut().check_end_names = false;
124
125        let mut depth = if from == 0 { 0u32 } else { 1 };
126        let mut current: Option<Element> = None;
127        let mut field: Option<Field> = None;
128        let mut name_text: Option<String> = None;
129        loop {
130            let start = from + reader.buffer_position() as usize;
131            let event = match reader.read_event() {
132                Ok(Event::Eof) | Err(_) => break,
133                Ok(e) => e,
134            };
135            let end = from + reader.buffer_position() as usize;
136            let range = || lines.range(text, start, end);
137            let empty = matches!(event, Event::Empty(_));
138            match event {
139                Event::Start(e) | Event::Empty(e) if depth == 0 => {
140                    // The root: keep its namespace bindings.
141                    for a in e.attributes().flatten() {
142                        let key = String::from_utf8_lossy(a.key.as_ref());
143                        let prefix = if key == "xmlns" {
144                            Some("")
145                        } else {
146                            key.strip_prefix("xmlns:")
147                        };
148                        if let Some(p) = prefix {
149                            ix.namespaces.push((
150                                p.to_string(),
151                                String::from_utf8_lossy(&a.value).into_owned(),
152                            ));
153                        }
154                    }
155                    if !empty {
156                        depth = 1;
157                    }
158                }
159                Event::Start(e) | Event::Empty(e) if depth == 1 => {
160                    let tag = &text[start..end];
161                    let (id_kind, id_range, mrid) = match attr_value(tag, "rdf:ID")
162                        .map(|s| (IdKind::Id, s))
163                        .or_else(|| attr_value(tag, "rdf:about").map(|s| (IdKind::About, s)))
164                    {
165                        Some((kind, (vs, ve))) => (
166                            Some(kind),
167                            Some(lines.range(text, start + vs, start + ve)),
168                            mrid_of(&tag[vs..ve]).to_string(),
169                        ),
170                        None => (None, None, String::new()),
171                    };
172                    let el = Element {
173                        qname: String::from_utf8_lossy(e.name().as_ref()).into_owned(),
174                        mrid,
175                        id_kind,
176                        head: range(),
177                        id_range,
178                        full: range(),
179                        fields: Vec::new(),
180                        name: None,
181                    };
182                    if !empty {
183                        current = Some(el);
184                        depth = 2;
185                    } else {
186                        ix.elements.push(el);
187                    }
188                }
189                Event::Start(e) | Event::Empty(e) if depth == 2 => {
190                    let tag = &text[start..end];
191                    let resource = attr_value(tag, "rdf:resource").map(|(vs, ve)| {
192                        (
193                            mrid_of(&tag[vs..ve]).to_string(),
194                            lines.range(text, start + vs, start + ve),
195                        )
196                    });
197                    let f = Field {
198                        qname: String::from_utf8_lossy(e.name().as_ref()).into_owned(),
199                        head: range(),
200                        full: range(),
201                        resource,
202                    };
203                    if let Some(el) = current.as_mut() {
204                        if !empty {
205                            name_text = (f.key() == "IdentifiedObject.name").then(String::new);
206                            field = Some(f);
207                        } else {
208                            el.fields.push(f);
209                        }
210                    }
211                    if !empty {
212                        depth = 3;
213                    }
214                }
215                Event::Start(_) => depth += 1,
216                Event::Text(t) if depth == 3 => {
217                    if let Some(name) = name_text.as_mut() {
218                        name.push_str(&t.unescape().unwrap_or_default());
219                    }
220                }
221                Event::CData(t) if depth == 3 => {
222                    if let Some(name) = name_text.as_mut() {
223                        name.push_str(&String::from_utf8_lossy(&t));
224                    }
225                }
226                Event::End(_) => {
227                    depth = depth.saturating_sub(1);
228                    match depth {
229                        2 => {
230                            if let (Some(el), Some(mut f)) = (current.as_mut(), field.take()) {
231                                f.full.end = range().end;
232                                if let Some(name) = name_text.take() {
233                                    el.name = Some(name.trim().to_string());
234                                }
235                                // A bare `<` being typed parses as a nameless tag.
236                                if !f.qname.is_empty() {
237                                    el.fields.push(f);
238                                }
239                            }
240                        }
241                        1 => {
242                            if let Some(mut el) = current.take() {
243                                el.full.end = range().end;
244                                ix.elements.push(el);
245                            }
246                        }
247                        _ => {}
248                    }
249                }
250                _ => {}
251            }
252        }
253        // A document cut short — or with a tag left half-typed, which
254        // swallows what follows — keeps its open element, to the end.
255        let cut = current.is_some();
256        if let Some(mut el) = current {
257            el.full.end = lines.position(text, within.end);
258            if let Some(f) = field.filter(|f| !f.qname.is_empty()) {
259                el.fields.push(f);
260            }
261            ix.elements.push(el);
262        }
263        cut
264    }
265}
266
267impl Index {
268    /// The index of `new`: this index's text, `old`, with `edits` applied (each placed in `old` as
269    /// it was), the lines of each counted. Only what the edits changed is read again, widened to
270    /// whole elements and lines; the elements after it keep theirs, moved by the lines it added or
271    /// took. Some 0.02 s for an edit of RealGrid's EQ file, where reading it whole takes 0.5 s.
272    /// With the mRIDs of the objects written where the edits are, before and after them: those
273    /// they touched.
274    ///
275    /// `Err` gives this index back for an edit around the objects (the XML declaration, the root
276    /// element) or one that leaves an element open: read `new` whole.
277    pub fn edited(
278        mut self,
279        old: &str,
280        old_lines: &LineIndex,
281        new: &str,
282        new_lines: &LineIndex,
283        edits: &[TextEdit],
284    ) -> Result<(Index, Vec<String>), Index> {
285        let els = &self.elements;
286        let (Some(first), Some(root_end)) = (els.first(), old.rfind("</")) else {
287            return Err(self);
288        };
289        let first = old_lines.offset(old, first.full.start);
290        let mut spans: Vec<(usize, usize, isize)> = edits
291            .iter()
292            .map(|e| {
293                let (s, t) = (
294                    old_lines.offset(old, e.range.start),
295                    old_lines.offset(old, e.range.end),
296                );
297                (s, t, e.new_text.len() as isize - (t - s) as isize)
298            })
299            .collect();
300        spans.sort_unstable();
301        if spans.is_empty() {
302            return Ok((self, Vec::new()));
303        }
304        if spans.iter().any(|&(s, t, _)| s < first || t > root_end) {
305            return Err(self);
306        }
307        let start_of = |i: usize| old_lines.offset(old, els[i].full.start);
308        let end_of = |i: usize| old_lines.offset(old, els[i].full.end);
309        // The elements meeting [from, to): their places.
310        let meeting = |from: usize, to: usize| {
311            let at = old_lines.position(old, from);
312            let i = els.partition_point(|e| e.full.end <= at);
313            let mut j = i;
314            while j < els.len() && start_of(j) < to.max(from + 1) {
315                j += 1;
316            }
317            (i, j)
318        };
319        // Windows over whole elements and lines: (from, to) in `old`, the elements in them, and
320        // how much longer the edits in them make them.
321        let mut windows: Vec<(usize, usize, usize, usize, isize)> = Vec::new();
322        for &(s, t, d) in &spans {
323            let (mut from, mut to) = (s, t);
324            loop {
325                let (i, j) = meeting(from, to);
326                let (f, e) = if i < j {
327                    (from.min(start_of(i)), to.max(end_of(j - 1)))
328                } else {
329                    (from, to)
330                };
331                // From the start of its line to the start of the next.
332                let f = old[..f].rfind('\n').map_or(0, |k| k + 1).max(first);
333                let at_line_start = e == 0 || old.as_bytes()[e - 1] == b'\n';
334                let e = if at_line_start {
335                    e
336                } else {
337                    old[e..].find('\n').map_or(root_end, |k| e + k + 1)
338                }
339                .min(root_end);
340                if (f, e) == (from, to) {
341                    break;
342                }
343                (from, to) = (f, e);
344            }
345            let (i, j) = meeting(from, to);
346            match windows.last_mut() {
347                Some(w) if from <= w.1 => {
348                    w.1 = w.1.max(to);
349                    w.3 = w.3.max(j);
350                    w.4 += d;
351                }
352                _ => windows.push((from, to, i, j, d)),
353            }
354        }
355        // Each window read again in `new`.
356        let mut read = Vec::with_capacity(windows.len());
357        let mut moved = 0isize;
358        for &(from, to, _, _, d) in &windows {
359            let at = (from as isize + moved) as usize;
360            let end = (to as isize + moved + d) as usize;
361            let mut ix = Index::default();
362            if end > new.len() || scan(new, new_lines, at..end, &mut ix) {
363                return Err(self);
364            }
365            let lines = |t: &str| t.bytes().filter(|&b| b == b'\n').count() as i64;
366            read.push((ix.elements, lines(&new[at..end]) - lines(&old[from..to])));
367            moved += d;
368        }
369        let mut touched = Vec::new();
370        let mut out = Vec::with_capacity(self.elements.len());
371        let mut old_els = std::mem::take(&mut self.elements)
372            .into_iter()
373            .enumerate()
374            .peekable();
375        let mut shift = 0i64;
376        for (&(_, _, i, j, _), (elements, lines)) in windows.iter().zip(read) {
377            while let Some((_, mut e)) = old_els.next_if(|(k, _)| *k < i) {
378                e.shift(shift);
379                out.push(e);
380            }
381            while let Some((_, e)) = old_els.next_if(|(k, _)| *k < j) {
382                touched.push(e.mrid);
383            }
384            touched.extend(elements.iter().map(|e| e.mrid.clone()));
385            out.extend(elements);
386            shift += lines;
387        }
388        for (_, mut e) in old_els {
389            e.shift(shift);
390            out.push(e);
391        }
392        self.elements = out;
393        self.by_mrid = OnceLock::new();
394        Ok((self, touched))
395    }
396
397    /// The elements writing the object `mrid`, in document order.
398    pub fn of(&self, mrid: &str) -> impl Iterator<Item = &Element> {
399        self.places_of(mrid)
400            .iter()
401            .map(|&i| &self.elements[i as usize])
402    }
403
404    /// The places in `elements` of those writing the object `mrid`, in document order.
405    pub fn places_of(&self, mrid: &str) -> &[u32] {
406        let by = self.by_mrid.get_or_init(|| {
407            let mut by: FastMap<String, Vec<u32>> = FastMap::default();
408            for (i, e) in self.elements.iter().enumerate() {
409                by.entry(e.mrid.clone()).or_default().push(i as u32);
410            }
411            by
412        });
413        by.get(mrid).map_or(&[][..], Vec::as_slice)
414    }
415
416    /// The namespace IRI `prefix` is bound to at the root.
417    pub fn namespace(&self, prefix: &str) -> Option<&str> {
418        self.namespaces
419            .iter()
420            .find(|(p, _)| p == prefix)
421            .map(|(_, ns)| ns.as_str())
422    }
423
424    /// The prefix bound to `ns` at the root.
425    pub fn prefix_of(&self, ns: &str) -> Option<&str> {
426        self.namespaces
427            .iter()
428            .find(|(_, n)| n == ns)
429            .map(|(p, _)| p.as_str())
430    }
431
432    /// The class of an element written `qname` here: by its prefix's namespace, else by its
433    /// local name alone.
434    pub fn class_of(&self, qname: &str) -> Option<&'static ClassDef> {
435        let reg = type_registry();
436        self.namespace(prefix(qname))
437            .and_then(|ns| reg.ns_table(ns))
438            .and_then(|t| t.get(local(qname)).copied())
439            .or_else(|| reg.bare().get(local(qname)).copied())
440    }
441
442    /// The element whose start-to-end span contains `pos`.
443    pub fn element_at(&self, pos: Position) -> Option<&Element> {
444        // Elements are in document order and do not overlap.
445        let i = self.elements.partition_point(|e| e.full.end < pos);
446        self.elements.get(i).filter(|e| contains(e.full, pos))
447    }
448}
449
450/// The byte span of attribute `name`'s value within a start tag, without its
451/// quotes.
452fn attr_value(tag: &str, name: &str) -> Option<(usize, usize)> {
453    let bytes = tag.as_bytes();
454    let mut from = 0;
455    while let Some(i) = tag[from..].find(name).map(|i| i + from) {
456        from = i + name.len();
457        // A whole attribute name: preceded by whitespace, followed by `=`.
458        if i == 0 || !bytes[i - 1].is_ascii_whitespace() {
459            continue;
460        }
461        let rest = tag[from..].trim_start();
462        let Some(rest) = rest.strip_prefix('=') else {
463            continue;
464        };
465        let rest = rest.trim_start();
466        let quote = rest.chars().next()?;
467        if quote != '"' && quote != '\'' {
468            continue;
469        }
470        let vs = tag.len() - rest.len() + 1;
471        let ve = vs + tag[vs..].find(quote)?;
472        return Some((vs, ve));
473    }
474    None
475}
476
477#[cfg(test)]
478mod tests {
479    use super::*;
480
481    const DOC: &str = r##"<?xml version="1.0" encoding="UTF-8"?>
482<rdf:RDF xmlns:cim="http://iec.ch/TC57/CIM100#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
483  <cim:ACLineSegment rdf:ID="_line">
484    <cim:IdentifiedObject.name>Line &amp; 1</cim:IdentifiedObject.name>
485    <cim:ACLineSegment.r>0.5</cim:ACLineSegment.r>
486    <cim:ConductingEquipment.BaseVoltage rdf:resource="#_bv"/>
487  </cim:ACLineSegment>
488  <cim:BaseVoltage
489      rdf:about="urn:uuid:x#_bv" />
490</rdf:RDF>
491"##;
492
493    fn pos(line: u32, character: u32) -> Position {
494        Position { line, character }
495    }
496
497    #[test]
498    fn indexes_elements_fields_and_references() {
499        let ix = Index::build(DOC);
500        assert_eq!(ix.namespace("cim"), Some("http://iec.ch/TC57/CIM100#"));
501        assert_eq!(ix.elements.len(), 2);
502
503        let line = &ix.elements[0];
504        assert_eq!(
505            (line.qname.as_str(), line.mrid.as_str(), line.id_kind),
506            ("cim:ACLineSegment", "_line", Some(IdKind::Id))
507        );
508        assert_eq!(
509            line.id_range,
510            Some(Range {
511                start: pos(2, 29),
512                end: pos(2, 34)
513            })
514        );
515        assert_eq!(line.full.start, pos(2, 2));
516        assert_eq!(line.full.end, pos(6, 22));
517        assert_eq!(line.name.as_deref(), Some("Line & 1"));
518        let keys: Vec<&str> = line.fields.iter().map(Field::key).collect();
519        assert_eq!(
520            keys,
521            [
522                "IdentifiedObject.name",
523                "ACLineSegment.r",
524                "ConductingEquipment.BaseVoltage"
525            ]
526        );
527        assert_eq!(
528            line.fields[1].full,
529            Range {
530                start: pos(4, 4),
531                end: pos(4, 50)
532            }
533        );
534        let (target, at) = line.fields[2].resource.clone().unwrap();
535        assert_eq!(target, "_bv");
536        assert_eq!(
537            at,
538            Range {
539                start: pos(5, 55),
540                end: pos(5, 59)
541            }
542        );
543
544        let bv = &ix.elements[1];
545        assert_eq!((bv.mrid.as_str(), bv.id_kind), ("_bv", Some(IdKind::About)));
546        assert_eq!(
547            bv.head,
548            Range {
549                start: pos(7, 2),
550                end: pos(8, 35)
551            }
552        );
553
554        assert_eq!(
555            ix.element_at(pos(4, 10)).map(|e| e.mrid.as_str()),
556            Some("_line")
557        );
558        assert!(ix.element_at(pos(1, 3)).is_none());
559    }
560
561    #[test]
562    fn a_truncated_document_keeps_what_it_has() {
563        let cut = &DOC[..DOC.find("<cim:ACLineSegment.r>").unwrap() + 25];
564        let ix = Index::build(cut);
565        assert_eq!(ix.elements.len(), 1);
566        assert_eq!(ix.elements[0].mrid, "_line");
567        assert_eq!(
568            ix.elements[0].full.end,
569            LineIndex::new(cut).position(cut, cut.len())
570        );
571    }
572}