cimoxide-view 0.8.0

A CGMES or NC model set as views: its grid at substation level, laid out, and its objects as a tree, with validation findings on each; and its files as text: where each object is written, and edits across them
Documentation
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
//! Where things are written in an RDF/XML document.
//!
//! The decoder keeps no positions — it is the hot path, and nothing else
//! needs them — so an editor makes its own pass with quick-xml over each
//! document it shows. The index records, as [`Range`]s, every top-level
//! element (an object), its `rdf:ID` / `rdf:about`, its field elements and
//! their `rdf:resource` targets. mRIDs follow the decoder: the text after the
//! last `#`.
//!
//! A document being edited is often not well-formed; the pass stops at the
//! first syntax error and keeps what it has.

use std::sync::OnceLock;

use cimmodel::base::{ClassDef, FastMap};
use cimmodel::registry::type_registry;
use quick_xml::Reader;
use quick_xml::events::Event;

use crate::mrid_of;
pub use crate::text::{LineIndex, Position, Range, TextEdit, contains};

/// `rdf:ID` defines an object; `rdf:about` describes one defined elsewhere.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IdKind {
    Id,
    About,
}

#[derive(Debug)]
pub struct Element {
    /// The tag as written, e.g. `cim:ACLineSegment`.
    pub qname: String,
    pub mrid: String,
    pub id_kind: Option<IdKind>,
    /// The start tag.
    pub head: Range,
    /// The value of `rdf:ID` / `rdf:about`, without quotes.
    pub id_range: Option<Range>,
    /// Start tag to end tag.
    pub full: Range,
    pub fields: Vec<Field>,
    /// `IdentifiedObject.name`, for labels.
    pub name: Option<String>,
}

impl Element {
    /// Moved down by `lines` (up, if negative), as text inserted above it moves it.
    fn shift(&mut self, lines: i64) {
        if lines == 0 {
            return;
        }
        let mut ranges: Vec<&mut Range> = vec![&mut self.head, &mut self.full];
        ranges.extend(self.id_range.as_mut());
        for f in &mut self.fields {
            ranges.push(&mut f.head);
            ranges.push(&mut f.full);
            ranges.extend(f.resource.as_mut().map(|(_, r)| r));
        }
        for r in ranges {
            for p in [&mut r.start, &mut r.end] {
                p.line = (p.line as i64 + lines) as u32;
            }
        }
    }
}

#[derive(Debug)]
pub struct Field {
    /// The tag as written, e.g. `cim:ACLineSegment.r`.
    pub qname: String,
    /// The start tag.
    pub head: Range,
    /// Start tag to end tag.
    pub full: Range,
    /// The `rdf:resource` target as an mRID, and the range of its value.
    pub resource: Option<(String, Range)>,
}

impl Field {
    /// The field key the decoder stores this field under: the local name.
    pub fn key(&self) -> &str {
        local(&self.qname)
    }
}

#[derive(Debug, Default)]
pub struct Index {
    /// `xmlns` bindings of the root element: (prefix, IRI); `""` for the
    /// default namespace.
    pub namespaces: Vec<(String, String)>,
    pub elements: Vec<Element>,
    /// The elements by mRID, by their place in `elements`: made on the first
    /// [`Index::of`].
    by_mrid: OnceLock<FastMap<String, Vec<u32>>>,
}

/// The local part of a qualified name.
pub fn local(qname: &str) -> &str {
    qname.rsplit_once(':').map_or(qname, |(_, l)| l)
}

/// The prefix of a qualified name, `""` when it has none.
pub fn prefix(qname: &str) -> &str {
    qname.split_once(':').map_or("", |(p, _)| p)
}

impl Index {
    pub fn build(text: &str) -> Self {
        let mut ix = Index::default();
        scan(text, &LineIndex::new(text), 0..text.len(), &mut ix);
        ix
    }
}

/// The elements written in `text[within]` added to `ix`, their places those in `text` (whose lines
/// are `lines`). From the start of `text`, the root's namespaces too; elsewhere, `within` holds
/// whole objects. Whether it ended inside an element: cut short.
fn scan(text: &str, lines: &LineIndex, within: std::ops::Range<usize>, ix: &mut Index) -> bool {
    {
        let from = within.start;
        let mut reader = Reader::from_str(&text[within.clone()]);
        reader.config_mut().check_end_names = false;

        let mut depth = if from == 0 { 0u32 } else { 1 };
        let mut current: Option<Element> = None;
        let mut field: Option<Field> = None;
        let mut name_text: Option<String> = None;
        loop {
            let start = from + reader.buffer_position() as usize;
            let event = match reader.read_event() {
                Ok(Event::Eof) | Err(_) => break,
                Ok(e) => e,
            };
            let end = from + reader.buffer_position() as usize;
            let range = || lines.range(text, start, end);
            let empty = matches!(event, Event::Empty(_));
            match event {
                Event::Start(e) | Event::Empty(e) if depth == 0 => {
                    // The root: keep its namespace bindings.
                    for a in e.attributes().flatten() {
                        let key = String::from_utf8_lossy(a.key.as_ref());
                        let prefix = if key == "xmlns" {
                            Some("")
                        } else {
                            key.strip_prefix("xmlns:")
                        };
                        if let Some(p) = prefix {
                            ix.namespaces.push((
                                p.to_string(),
                                String::from_utf8_lossy(&a.value).into_owned(),
                            ));
                        }
                    }
                    if !empty {
                        depth = 1;
                    }
                }
                Event::Start(e) | Event::Empty(e) if depth == 1 => {
                    let tag = &text[start..end];
                    let (id_kind, id_range, mrid) = match attr_value(tag, "rdf:ID")
                        .map(|s| (IdKind::Id, s))
                        .or_else(|| attr_value(tag, "rdf:about").map(|s| (IdKind::About, s)))
                    {
                        Some((kind, (vs, ve))) => (
                            Some(kind),
                            Some(lines.range(text, start + vs, start + ve)),
                            mrid_of(&tag[vs..ve]).to_string(),
                        ),
                        None => (None, None, String::new()),
                    };
                    let el = Element {
                        qname: String::from_utf8_lossy(e.name().as_ref()).into_owned(),
                        mrid,
                        id_kind,
                        head: range(),
                        id_range,
                        full: range(),
                        fields: Vec::new(),
                        name: None,
                    };
                    if !empty {
                        current = Some(el);
                        depth = 2;
                    } else {
                        ix.elements.push(el);
                    }
                }
                Event::Start(e) | Event::Empty(e) if depth == 2 => {
                    let tag = &text[start..end];
                    let resource = attr_value(tag, "rdf:resource").map(|(vs, ve)| {
                        (
                            mrid_of(&tag[vs..ve]).to_string(),
                            lines.range(text, start + vs, start + ve),
                        )
                    });
                    let f = Field {
                        qname: String::from_utf8_lossy(e.name().as_ref()).into_owned(),
                        head: range(),
                        full: range(),
                        resource,
                    };
                    if let Some(el) = current.as_mut() {
                        if !empty {
                            name_text = (f.key() == "IdentifiedObject.name").then(String::new);
                            field = Some(f);
                        } else {
                            el.fields.push(f);
                        }
                    }
                    if !empty {
                        depth = 3;
                    }
                }
                Event::Start(_) => depth += 1,
                Event::Text(t) if depth == 3 => {
                    if let Some(name) = name_text.as_mut() {
                        name.push_str(&t.unescape().unwrap_or_default());
                    }
                }
                Event::CData(t) if depth == 3 => {
                    if let Some(name) = name_text.as_mut() {
                        name.push_str(&String::from_utf8_lossy(&t));
                    }
                }
                Event::End(_) => {
                    depth = depth.saturating_sub(1);
                    match depth {
                        2 => {
                            if let (Some(el), Some(mut f)) = (current.as_mut(), field.take()) {
                                f.full.end = range().end;
                                if let Some(name) = name_text.take() {
                                    el.name = Some(name.trim().to_string());
                                }
                                // A bare `<` being typed parses as a nameless tag.
                                if !f.qname.is_empty() {
                                    el.fields.push(f);
                                }
                            }
                        }
                        1 => {
                            if let Some(mut el) = current.take() {
                                el.full.end = range().end;
                                ix.elements.push(el);
                            }
                        }
                        _ => {}
                    }
                }
                _ => {}
            }
        }
        // A document cut short — or with a tag left half-typed, which
        // swallows what follows — keeps its open element, to the end.
        let cut = current.is_some();
        if let Some(mut el) = current {
            el.full.end = lines.position(text, within.end);
            if let Some(f) = field.filter(|f| !f.qname.is_empty()) {
                el.fields.push(f);
            }
            ix.elements.push(el);
        }
        cut
    }
}

impl Index {
    /// The index of `new`: this index's text, `old`, with `edits` applied (each placed in `old` as
    /// it was), the lines of each counted. Only what the edits changed is read again, widened to
    /// whole elements and lines; the elements after it keep theirs, moved by the lines it added or
    /// took. Some 0.02 s for an edit of RealGrid's EQ file, where reading it whole takes 0.5 s.
    /// With the mRIDs of the objects written where the edits are, before and after them: those
    /// they touched.
    ///
    /// `Err` gives this index back for an edit around the objects (the XML declaration, the root
    /// element) or one that leaves an element open: read `new` whole.
    pub fn edited(
        mut self,
        old: &str,
        old_lines: &LineIndex,
        new: &str,
        new_lines: &LineIndex,
        edits: &[TextEdit],
    ) -> Result<(Index, Vec<String>), Index> {
        let els = &self.elements;
        let (Some(first), Some(root_end)) = (els.first(), old.rfind("</")) else {
            return Err(self);
        };
        let first = old_lines.offset(old, first.full.start);
        let mut spans: Vec<(usize, usize, isize)> = edits
            .iter()
            .map(|e| {
                let (s, t) = (
                    old_lines.offset(old, e.range.start),
                    old_lines.offset(old, e.range.end),
                );
                (s, t, e.new_text.len() as isize - (t - s) as isize)
            })
            .collect();
        spans.sort_unstable();
        if spans.is_empty() {
            return Ok((self, Vec::new()));
        }
        if spans.iter().any(|&(s, t, _)| s < first || t > root_end) {
            return Err(self);
        }
        let start_of = |i: usize| old_lines.offset(old, els[i].full.start);
        let end_of = |i: usize| old_lines.offset(old, els[i].full.end);
        // The elements meeting [from, to): their places.
        let meeting = |from: usize, to: usize| {
            let at = old_lines.position(old, from);
            let i = els.partition_point(|e| e.full.end <= at);
            let mut j = i;
            while j < els.len() && start_of(j) < to.max(from + 1) {
                j += 1;
            }
            (i, j)
        };
        // Windows over whole elements and lines: (from, to) in `old`, the elements in them, and
        // how much longer the edits in them make them.
        let mut windows: Vec<(usize, usize, usize, usize, isize)> = Vec::new();
        for &(s, t, d) in &spans {
            let (mut from, mut to) = (s, t);
            loop {
                let (i, j) = meeting(from, to);
                let (f, e) = if i < j {
                    (from.min(start_of(i)), to.max(end_of(j - 1)))
                } else {
                    (from, to)
                };
                // From the start of its line to the start of the next.
                let f = old[..f].rfind('\n').map_or(0, |k| k + 1).max(first);
                let at_line_start = e == 0 || old.as_bytes()[e - 1] == b'\n';
                let e = if at_line_start {
                    e
                } else {
                    old[e..].find('\n').map_or(root_end, |k| e + k + 1)
                }
                .min(root_end);
                if (f, e) == (from, to) {
                    break;
                }
                (from, to) = (f, e);
            }
            let (i, j) = meeting(from, to);
            match windows.last_mut() {
                Some(w) if from <= w.1 => {
                    w.1 = w.1.max(to);
                    w.3 = w.3.max(j);
                    w.4 += d;
                }
                _ => windows.push((from, to, i, j, d)),
            }
        }
        // Each window read again in `new`.
        let mut read = Vec::with_capacity(windows.len());
        let mut moved = 0isize;
        for &(from, to, _, _, d) in &windows {
            let at = (from as isize + moved) as usize;
            let end = (to as isize + moved + d) as usize;
            let mut ix = Index::default();
            if end > new.len() || scan(new, new_lines, at..end, &mut ix) {
                return Err(self);
            }
            let lines = |t: &str| t.bytes().filter(|&b| b == b'\n').count() as i64;
            read.push((ix.elements, lines(&new[at..end]) - lines(&old[from..to])));
            moved += d;
        }
        let mut touched = Vec::new();
        let mut out = Vec::with_capacity(self.elements.len());
        let mut old_els = std::mem::take(&mut self.elements)
            .into_iter()
            .enumerate()
            .peekable();
        let mut shift = 0i64;
        for (&(_, _, i, j, _), (elements, lines)) in windows.iter().zip(read) {
            while let Some((_, mut e)) = old_els.next_if(|(k, _)| *k < i) {
                e.shift(shift);
                out.push(e);
            }
            while let Some((_, e)) = old_els.next_if(|(k, _)| *k < j) {
                touched.push(e.mrid);
            }
            touched.extend(elements.iter().map(|e| e.mrid.clone()));
            out.extend(elements);
            shift += lines;
        }
        for (_, mut e) in old_els {
            e.shift(shift);
            out.push(e);
        }
        self.elements = out;
        self.by_mrid = OnceLock::new();
        Ok((self, touched))
    }

    /// The elements writing the object `mrid`, in document order.
    pub fn of(&self, mrid: &str) -> impl Iterator<Item = &Element> {
        self.places_of(mrid)
            .iter()
            .map(|&i| &self.elements[i as usize])
    }

    /// The places in `elements` of those writing the object `mrid`, in document order.
    pub fn places_of(&self, mrid: &str) -> &[u32] {
        let by = self.by_mrid.get_or_init(|| {
            let mut by: FastMap<String, Vec<u32>> = FastMap::default();
            for (i, e) in self.elements.iter().enumerate() {
                by.entry(e.mrid.clone()).or_default().push(i as u32);
            }
            by
        });
        by.get(mrid).map_or(&[][..], Vec::as_slice)
    }

    /// The namespace IRI `prefix` is bound to at the root.
    pub fn namespace(&self, prefix: &str) -> Option<&str> {
        self.namespaces
            .iter()
            .find(|(p, _)| p == prefix)
            .map(|(_, ns)| ns.as_str())
    }

    /// The prefix bound to `ns` at the root.
    pub fn prefix_of(&self, ns: &str) -> Option<&str> {
        self.namespaces
            .iter()
            .find(|(_, n)| n == ns)
            .map(|(p, _)| p.as_str())
    }

    /// The class of an element written `qname` here: by its prefix's namespace, else by its
    /// local name alone.
    pub fn class_of(&self, qname: &str) -> Option<&'static ClassDef> {
        let reg = type_registry();
        self.namespace(prefix(qname))
            .and_then(|ns| reg.ns_table(ns))
            .and_then(|t| t.get(local(qname)).copied())
            .or_else(|| reg.bare().get(local(qname)).copied())
    }

    /// The element whose start-to-end span contains `pos`.
    pub fn element_at(&self, pos: Position) -> Option<&Element> {
        // Elements are in document order and do not overlap.
        let i = self.elements.partition_point(|e| e.full.end < pos);
        self.elements.get(i).filter(|e| contains(e.full, pos))
    }
}

/// The byte span of attribute `name`'s value within a start tag, without its
/// quotes.
fn attr_value(tag: &str, name: &str) -> Option<(usize, usize)> {
    let bytes = tag.as_bytes();
    let mut from = 0;
    while let Some(i) = tag[from..].find(name).map(|i| i + from) {
        from = i + name.len();
        // A whole attribute name: preceded by whitespace, followed by `=`.
        if i == 0 || !bytes[i - 1].is_ascii_whitespace() {
            continue;
        }
        let rest = tag[from..].trim_start();
        let Some(rest) = rest.strip_prefix('=') else {
            continue;
        };
        let rest = rest.trim_start();
        let quote = rest.chars().next()?;
        if quote != '"' && quote != '\'' {
            continue;
        }
        let vs = tag.len() - rest.len() + 1;
        let ve = vs + tag[vs..].find(quote)?;
        return Some((vs, ve));
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;

    const DOC: &str = r##"<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF xmlns:cim="http://iec.ch/TC57/CIM100#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
  <cim:ACLineSegment rdf:ID="_line">
    <cim:IdentifiedObject.name>Line &amp; 1</cim:IdentifiedObject.name>
    <cim:ACLineSegment.r>0.5</cim:ACLineSegment.r>
    <cim:ConductingEquipment.BaseVoltage rdf:resource="#_bv"/>
  </cim:ACLineSegment>
  <cim:BaseVoltage
      rdf:about="urn:uuid:x#_bv" />
</rdf:RDF>
"##;

    fn pos(line: u32, character: u32) -> Position {
        Position { line, character }
    }

    #[test]
    fn indexes_elements_fields_and_references() {
        let ix = Index::build(DOC);
        assert_eq!(ix.namespace("cim"), Some("http://iec.ch/TC57/CIM100#"));
        assert_eq!(ix.elements.len(), 2);

        let line = &ix.elements[0];
        assert_eq!(
            (line.qname.as_str(), line.mrid.as_str(), line.id_kind),
            ("cim:ACLineSegment", "_line", Some(IdKind::Id))
        );
        assert_eq!(
            line.id_range,
            Some(Range {
                start: pos(2, 29),
                end: pos(2, 34)
            })
        );
        assert_eq!(line.full.start, pos(2, 2));
        assert_eq!(line.full.end, pos(6, 22));
        assert_eq!(line.name.as_deref(), Some("Line & 1"));
        let keys: Vec<&str> = line.fields.iter().map(Field::key).collect();
        assert_eq!(
            keys,
            [
                "IdentifiedObject.name",
                "ACLineSegment.r",
                "ConductingEquipment.BaseVoltage"
            ]
        );
        assert_eq!(
            line.fields[1].full,
            Range {
                start: pos(4, 4),
                end: pos(4, 50)
            }
        );
        let (target, at) = line.fields[2].resource.clone().unwrap();
        assert_eq!(target, "_bv");
        assert_eq!(
            at,
            Range {
                start: pos(5, 55),
                end: pos(5, 59)
            }
        );

        let bv = &ix.elements[1];
        assert_eq!((bv.mrid.as_str(), bv.id_kind), ("_bv", Some(IdKind::About)));
        assert_eq!(
            bv.head,
            Range {
                start: pos(7, 2),
                end: pos(8, 35)
            }
        );

        assert_eq!(
            ix.element_at(pos(4, 10)).map(|e| e.mrid.as_str()),
            Some("_line")
        );
        assert!(ix.element_at(pos(1, 3)).is_none());
    }

    #[test]
    fn a_truncated_document_keeps_what_it_has() {
        let cut = &DOC[..DOC.find("<cim:ACLineSegment.r>").unwrap() + 25];
        let ix = Index::build(cut);
        assert_eq!(ix.elements.len(), 1);
        assert_eq!(ix.elements[0].mrid, "_line");
        assert_eq!(
            ix.elements[0].full.end,
            LineIndex::new(cut).position(cut, cut.len())
        );
    }
}