Skip to main content

cimview/
edit.rs

1//! Edits across a model set, as text edits for whoever holds the files to
2//! apply: renaming an mRID, deleting objects and adding a field a finding
3//! says is missing; and the objects a reference can name, the likeliest
4//! first; adding an object in a container. They change the files as
5//! written, keeping everything else of them, and reach every file of the
6//! set: an object's EQ, SSH and SV elements and every reference to it.
7//!
8//! The caller gives the files as they are now, each named as it likes (a
9//! URL, a file name), with its [`Index`]; the edits come back by that name.
10
11use std::collections::{HashMap, HashSet};
12
13use cimmodel::base::AttrKind;
14use cimmodel::registry::type_registry;
15
16use crate::index::{IdKind, Index, local};
17use crate::text::{LineIndex, Position, Range, TextEdit, contains};
18use crate::tree::{CONTAINED, Tree};
19
20/// One file of the set, as it is now.
21pub struct File<'a> {
22    /// Whatever names it for the caller.
23    pub name: &'a str,
24    pub text: &'a str,
25    pub lines: &'a LineIndex,
26    pub index: &'a Index,
27}
28
29/// Edits by file, in the order the files were given; only files that change.
30pub type Edits<'a> = Vec<(&'a str, Vec<TextEdit>)>;
31
32impl File<'_> {
33    /// The last `len` bytes of `r`: an mRID at the end of the value written
34    /// (after `#`, or the whole of `_x` or `urn:uuid:x`).
35    fn suffix(&self, r: Range, len: usize) -> Range {
36        let end = self.lines.offset(self.text, r.end);
37        Range::new(self.lines.position(self.text, end.saturating_sub(len)), r.end)
38    }
39
40    /// `r` widened to whole lines when nothing else is written on them.
41    fn lines_of(&self, r: Range) -> Range {
42        let (text, start, end) = (self.text, self.lines.offset(self.text, r.start), self.lines.offset(self.text, r.end));
43        let line_start = text[..start].rfind('\n').map_or(0, |i| i + 1);
44        let line_end = text[end..].find('\n').map_or(text.len(), |i| end + i + 1);
45        if text[line_start..start].trim().is_empty() && text[end..line_end].trim().is_empty() {
46            self.lines.range(text, line_start, line_end)
47        } else {
48            r
49        }
50    }
51
52    /// The text of a field written `<q>text</q>`, and its range.
53    fn field_text(&self, head: Range, full: Range, qname: &str) -> Option<(&str, Range)> {
54        let start = self.lines.offset(self.text, head.end);
55        let end = self.lines.offset(self.text, full.end).checked_sub(qname.len() + 3)?;
56        let value = self.text.get(start..end)?;
57        (!value.contains('<')).then(|| (value, self.lines.range(self.text, start, end)))
58    }
59}
60
61/// The mRID at `pos` in the file `name` — an element's `rdf:ID`/`rdf:about`,
62/// or an `rdf:resource` — and the range of it as written; anywhere else in an
63/// element's start tag, that element's.
64pub fn prepare_rename(files: &[File], name: &str, pos: Position) -> Option<(Range, String)> {
65    let file = files.iter().find(|f| f.name == name)?;
66    let el = file.index.element_at(pos)?;
67    if let Some((mrid, r)) = el.fields.iter().filter_map(|f| f.resource.as_ref()).find(|(_, r)| contains(*r, pos)) {
68        return Some((file.suffix(*r, mrid.len()), mrid.clone()));
69    }
70    let id = el.id_range?;
71    (contains(el.head, pos) && !el.mrid.is_empty()).then(|| (file.suffix(id, el.mrid.len()), el.mrid.clone()))
72}
73
74/// Rename mRID `old` to `new` in every file: each element's `rdf:ID` or
75/// `rdf:about`, each `rdf:resource` to it, and an `IdentifiedObject.mRID`
76/// (or a class's own `….mRID`) that writes it (without its leading `_`, as
77/// CGMES 3 does, if so).
78pub fn rename<'a>(files: &[File<'a>], old: &str, new: &str) -> Result<Edits<'a>, String> {
79    let new = new.trim();
80    if new.is_empty() || new.contains(|c: char| c.is_whitespace() || "\"'<>&#".contains(c)) {
81        return Err(format!("`{new}` cannot be an mRID: no spaces, quotes, `<`, `>`, `&` or `#`"));
82    }
83    let defined = files.iter().flat_map(|f| &f.index.elements).any(|e| e.mrid == old && e.id_kind == Some(IdKind::Id));
84    let ncname = new.starts_with(|c: char| c.is_alphabetic() || c == '_') && !new.contains(':');
85    if defined && !ncname {
86        return Err(format!("`{new}` cannot be an `rdf:ID`: it must start with a letter or `_` and hold no `:`"));
87    }
88    if files.iter().flat_map(|f| &f.index.elements).any(|e| e.mrid == new) {
89        return Err(format!("the model set already has an object `{new}`"));
90    }
91    let mut changes = Vec::new();
92    for file in files {
93        let mut edits = Vec::new();
94        for el in &file.index.elements {
95            if el.mrid == old
96                && let Some(id) = el.id_range
97            {
98                edits.push(TextEdit::new(file.suffix(id, old.len()), new.into()));
99                for f in el.fields.iter().filter(|f| f.key().ends_with(".mRID")) {
100                    let Some((text, r)) = file.field_text(f.head, f.full, &f.qname) else { continue };
101                    let bare = |s: &str| s.strip_prefix('_').unwrap_or(s).to_string();
102                    if text.trim() == old {
103                        edits.push(TextEdit::new(r, new.into()));
104                    } else if text.trim() == bare(old) {
105                        edits.push(TextEdit::new(r, bare(new)));
106                    }
107                }
108            }
109            for (mrid, r) in el.fields.iter().filter_map(|f| f.resource.as_ref()) {
110                if mrid == old {
111                    edits.push(TextEdit::new(file.suffix(*r, old.len()), new.into()));
112                }
113            }
114        }
115        if !edits.is_empty() {
116            changes.push((file.name, edits));
117        }
118    }
119    Ok(changes)
120}
121
122/// What deleting objects changes: the elements writing them, in every file,
123/// and the fields referring to them from what stays. Whole lines go, so a
124/// client should show it before applying it.
125pub struct Deletion<'a> {
126    pub edits: Edits<'a>,
127    pub objects: usize,
128    pub references: usize,
129}
130
131/// Delete objects `ids`.
132pub fn delete<'a>(files: &[File<'a>], ids: &HashSet<&str>) -> Deletion<'a> {
133    let mut changes = Vec::new();
134    let (mut objects, mut references) = (HashSet::new(), 0);
135    for file in files {
136        let mut edits: Vec<TextEdit> = Vec::new();
137        let mut edit = |r: Range| edits.push(TextEdit::new(file.lines_of(r), String::new()));
138        for el in &file.index.elements {
139            if ids.contains(el.mrid.as_str()) {
140                objects.insert(el.mrid.as_str());
141                edit(el.full);
142                continue;
143            }
144            for f in &el.fields {
145                if f.resource.as_ref().is_some_and(|(m, _)| ids.contains(m.as_str())) {
146                    references += 1;
147                    edit(f.full);
148                }
149            }
150        }
151        if !edits.is_empty() {
152            changes.push((file.name, edits));
153        }
154    }
155    Deletion { edits: changes, objects: objects.len(), references }
156}
157
158/// A field to add: where, and where its value is once added.
159pub struct Addition {
160    /// The file it goes in, by its name.
161    pub file: String,
162    pub edit: TextEdit,
163    /// The inserted value (or where it goes), to select after the edit.
164    pub value: Range,
165    /// A reference, inserted empty: `rdf:resource="#"`.
166    pub reference: bool,
167}
168
169impl Addition {
170    /// The edit with the reference to `c` filled in.
171    pub fn naming(&self, c: &Candidate) -> TextEdit {
172        TextEdit::new(self.edit.range, self.edit.new_text.replacen("rdf:resource=\"#\"", &format!("rdf:resource=\"{}\"", c.reference()), 1))
173    }
174}
175
176/// The profile codes `file`'s header declares (`md:Model.profile`,
177/// `dcterms:conformsTo`), by the schemas' profile tables.
178fn profiles(file: &File) -> Vec<&'static str> {
179    let reg = type_registry();
180    let tables: Vec<&[(&str, &str)]> = ["cgmes", "nc"].iter().filter_map(|f| reg.schema(f)).map(|s| s.profiles).collect();
181    let Some(header) = file.index.elements.iter().find(|e| matches!(local(&e.qname), "FullModel" | "Dataset" | "DifferenceModel")) else { return Vec::new() };
182    header
183        .fields
184        .iter()
185        .filter(|f| matches!(f.key(), "Model.profile" | "conformsTo"))
186        .filter_map(|f| match &f.resource {
187            Some((uri, _)) => Some(uri.as_str()),
188            None => file.field_text(f.head, f.full, &f.qname).map(|(t, _)| t.trim()),
189        })
190        .filter_map(|uri| tables.iter().flat_map(|t| t.iter()).find(|(_, u)| *u == uri).map(|(code, _)| *code))
191        .collect()
192}
193
194/// Add field `key` to object `id`, which writes it nowhere: in the file
195/// (`prefer` first) whose profile carries it and that writes the object,
196/// after its last field, with a value to type over — the object's mRID for
197/// `IdentifiedObject.mRID`, `false`, `0`, an enumeration's first value, or
198/// none. `None` if a file writes it already, its class does not declare
199/// it, or no file fits.
200pub fn add_missing(files: &[File], prefer: &str, id: &str, key: &str) -> Option<Addition> {
201    addition(files, prefer, id, key, None)
202}
203
204/// [`add_missing`], with `given` as the value written (as [`set_field`] takes it) rather than
205/// one to type over.
206fn addition(files: &[File], prefer: &str, id: &str, key: &str, given: Option<&str>) -> Option<Addition> {
207    let reg = type_registry();
208    let sites: Vec<(&File, &crate::index::Element)> =
209        files.iter().flat_map(|f| f.index.elements.iter().filter(|e| e.mrid == id).map(move |e| (f, e))).collect();
210    if sites.iter().any(|(_, e)| e.fields.iter().any(|f| f.key() == key)) {
211        return None;
212    }
213    let (def_file, def) = sites.iter().max_by_key(|(_, e)| e.id_kind == Some(IdKind::Id))?;
214    let class = def_file.index.class_of(&def.qname)?;
215    let attr = reg.attr(class, key).filter(|a| a.used)?;
216    let fits = |f: &File| {
217        let declared = profiles(f);
218        declared.is_empty() || attr.origins.is_empty() || declared.iter().any(|p| attr.origins.contains(p))
219    };
220    let (file, el) = sites
221        .iter()
222        .filter(|(f, _)| fits(f))
223        .min_by_key(|(f, e)| (f.name != prefer, e.id_kind != Some(IdKind::Id)))?;
224    let tag = format!("{}:{}", file.index.prefix_of(attr.ns)?, attr.id);
225    let (open, value, close) = match attr.kind {
226        AttrKind::Literal => {
227            let value = match (attr.id, attr.xsd) {
228                _ if given.is_some() => escape(given.unwrap_or_default()),
229                ("IdentifiedObject.mRID", _) => id.strip_prefix('_').unwrap_or(id).to_string(),
230                (_, "boolean") => "false".into(),
231                (_, "double" | "float" | "decimal" | "integer" | "int" | "long" | "short") => "0".into(),
232                _ => String::new(),
233            };
234            (format!("<{tag}>"), value, format!("</{tag}>"))
235        }
236        AttrKind::Association => match given {
237            Some(target) => (format!("<{tag} rdf:resource=\""), reference(target), "\" />".into()),
238            None => (format!("<{tag} rdf:resource=\"#"), String::new(), "\" />".into()),
239        },
240        AttrKind::Enum => {
241            let first = reg.family_of(class.qualified).and_then(|f| reg.schema(f)).and_then(|s| s.enumeration(attr.range)).and_then(|e| e.values.first());
242            let value = given.map_or_else(|| first.map_or(String::new(), |v| v.id.to_string()), |v| enum_value(attr.range, v).to_string());
243            (format!("<{tag} rdf:resource=\"{}", attr.value_ns), value, "\" />".into())
244        }
245    };
246    // On a line of its own after the last field, indented as it is; else
247    // inside the element, a step in from it.
248    let (text, lines) = (file.text, file.lines);
249    let indent_of = |r: Range| {
250        let start = lines.offset(text, Position::new(r.start.line, 0));
251        let at = lines.offset(text, r.start);
252        text[start..at].chars().take_while(|c| c.is_whitespace()).collect::<String>()
253    };
254    let (at, indent) = match el.fields.last() {
255        Some(f) => (f.full.end, indent_of(f.head)),
256        None => {
257            let end = lines.offset(text, el.full.end);
258            let closing = end.checked_sub(el.qname.len() + 3).filter(|&c| text.get(c..end) == Some(&format!("</{}>", el.qname)))?;
259            (lines.position(text, closing), format!("{}  ", indent_of(el.head)))
260        }
261    };
262    // Lines end as the file's do.
263    let eol = if text.contains("\r\n") { "\r\n" } else { "\n" };
264    let new_text = if el.fields.is_empty() {
265        format!("  {open}{value}{close}{eol}{}", indent_of(el.head))
266    } else {
267        format!("{eol}{indent}{open}{value}{close}")
268    };
269    let utf16 = |s: &str| s.encode_utf16().count() as u32;
270    let start = if el.fields.is_empty() { Position::new(at.line, at.character + 2 + utf16(&open)) } else { Position::new(at.line + 1, utf16(&indent) + utf16(&open)) };
271    let value_range = Range::new(start, Position::new(start.line, start.character + utf16(&value)));
272    let reference = attr.kind == AttrKind::Association && given.is_none();
273    Some(Addition { file: file.name.to_string(), edit: TextEdit::new(Range::new(at, at), new_text), value: value_range, reference })
274}
275
276/// `text` as XML character data.
277fn escape(text: &str) -> String {
278    text.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;")
279}
280
281/// A reference to object `target` as written: `#_id`, or an IRI as it is.
282fn reference(target: &str) -> String {
283    if target.contains(':') { target.to_string() } else { format!("#{target}") }
284}
285
286/// An enumeration's value as its IRI ends: `WindingConnection.D`, from `D` or the whole name.
287fn enum_value<'v>(range: &str, value: &'v str) -> std::borrow::Cow<'v, str> {
288    let value = value.rsplit_once('#').map_or(value, |(_, v)| v);
289    if value.contains('.') { value.into() } else { format!("{range}.{value}").into() }
290}
291
292/// Set field `key` of object `id` to `value`: a literal's text (escaped here), a reference's
293/// object (its mRID, or an IRI), or an enumeration's value (`D`, or `WindingConnection.D`).
294/// Wherever a file writes the field, its value is replaced; where none does, it is added as
295/// [`add_missing`] adds it, `prefer` first. An error if the object's class does not declare it.
296pub fn set_field<'a>(files: &[File<'a>], prefer: &str, id: &str, key: &str, value: &str) -> Result<Edits<'a>, String> {
297    let reg = type_registry();
298    let (def_file, def) = files
299        .iter()
300        .flat_map(|f| f.index.elements.iter().filter(|e| e.mrid == id).map(move |e| (f, e)))
301        .max_by_key(|(_, e)| e.id_kind == Some(IdKind::Id))
302        .ok_or_else(|| format!("no file writes `{id}`"))?;
303    let class = def_file.index.class_of(&def.qname).ok_or_else(|| format!("`{}` is no class of the tables", def.qname))?;
304    let attr = reg.attr(class, key).ok_or_else(|| format!("{} has no field {key}", class.local))?;
305    let mut changes: Edits<'a> = Vec::new();
306    for file in files {
307        let mut edits = Vec::new();
308        for el in file.index.elements.iter().filter(|e| e.mrid == id) {
309            for f in el.fields.iter().filter(|f| f.key() == key) {
310                let edit = match (attr.kind, &f.resource) {
311                    (AttrKind::Literal, None) => match file.field_text(f.head, f.full, &f.qname) {
312                        Some((_, r)) => TextEdit::new(r, escape(value)),
313                        // `<x/>`: written anew.
314                        None => TextEdit::new(f.full, format!("<{q}>{}</{q}>", escape(value), q = f.qname)),
315                    },
316                    (AttrKind::Association, Some((_, r))) => TextEdit::new(*r, reference(value)),
317                    (AttrKind::Enum, Some((_, r))) => {
318                        let start = file.lines.offset(file.text, r.start);
319                        let end = file.lines.offset(file.text, r.end);
320                        let written = &file.text[start..end];
321                        // Its namespace as written, else the attribute's.
322                        let ns = written.rsplit_once('#').map_or(attr.value_ns.to_string(), |(ns, _)| format!("{ns}#"));
323                        TextEdit::new(*r, format!("{ns}{}", enum_value(attr.range, value)))
324                    }
325                    _ => return Err(format!("{key} is written in {} as it cannot be set", file.name)),
326                };
327                edits.push(edit);
328            }
329        }
330        if !edits.is_empty() {
331            changes.push((file.name, edits));
332        }
333    }
334    if changes.is_empty() {
335        let added = addition(files, prefer, id, key, Some(value)).ok_or_else(|| format!("no file of the set takes {key} for `{id}`"))?;
336        let name = files.iter().find(|f| f.name == added.file).map(|f| f.name).expect("one of the files");
337        changes.push((name, vec![added.edit]));
338    }
339    Ok(changes)
340}
341
342/// Remove field `key` from object `id` in every file writing it, its lines with it.
343pub fn remove_field<'a>(files: &[File<'a>], id: &str, key: &str) -> Edits<'a> {
344    let mut changes = Vec::new();
345    for file in files {
346        let edits: Vec<TextEdit> = file
347            .index
348            .elements
349            .iter()
350            .filter(|e| e.mrid == id)
351            .flat_map(|e| e.fields.iter().filter(|f| f.key() == key))
352            .map(|f| TextEdit::new(file.lines_of(f.full), String::new()))
353            .collect();
354        if !edits.is_empty() {
355            changes.push((file.name, edits));
356        }
357    }
358    changes
359}
360
361/// A field of `class` written as an element of `file`, its value as [`set_field`] takes it.
362fn field_element(file: &File, class: &'static cimmodel::base::ClassDef, key: &str, value: &str) -> Result<String, String> {
363    let attr = type_registry().attr(class, key).ok_or_else(|| format!("{} has no field {key}", class.local))?;
364    let prefix = file.index.prefix_of(attr.ns).ok_or_else(|| format!("{} binds no prefix to {}", file.name, attr.ns))?;
365    let tag = format!("{prefix}:{}", attr.id);
366    Ok(match attr.kind {
367        AttrKind::Literal => format!("<{tag}>{}</{tag}>", escape(value)),
368        AttrKind::Association => format!("<{tag} rdf:resource=\"{}\" />", reference(value)),
369        AttrKind::Enum => format!("<{tag} rdf:resource=\"{}{}\" />", attr.value_ns, enum_value(attr.range, value)),
370    })
371}
372
373/// `lines` (an element, unindented) inserted before the end tag of `file`'s root, indented as its
374/// elements are, in its line endings.
375fn at_end(file: &File, lines: &[String]) -> Result<TextEdit, String> {
376    let text = file.text;
377    let eol = if text.contains("\r\n") { "\r\n" } else { "\n" };
378    let root_end = text.rfind("</").ok_or("the file has no root end tag")?;
379    let line_start = text[..root_end].rfind('\n').map_or(0, |i| i + 1);
380    let indent = file.index.elements.last().map_or("  ".to_string(), |el| {
381        let head = file.lines.offset(text, el.head.start);
382        text[text[..head].rfind('\n').map_or(0, |i| i + 1)..head].to_string()
383    });
384    let at = file.lines.position(text, line_start);
385    let body: String = lines.iter().map(|l| format!("{indent}{l}{eol}")).collect();
386    Ok(TextEdit::new(Range::new(at, at), body))
387}
388
389/// A fresh mRID, `_` and a UUID from `random`, that the set does not have yet nor `taken`.
390fn fresh(files: &[File], taken: &HashSet<String>, random: &mut dyn FnMut() -> [u8; 16]) -> String {
391    loop {
392        let id = format!("_{}", uuid(random()));
393        if !taken.contains(&id) && !files.iter().any(|f| f.index.elements.iter().any(|e| e.mrid == id)) {
394            return id;
395        }
396    }
397}
398
399/// A new object of `class`, with `values` (field, value as [`set_field`] takes it) and its
400/// mRID as text where the class has a field for it (`IdentifiedObject.mRID`, or its own), written at the end of the file `into`, with an
401/// `rdf:ID` whose UUID is drawn from `random`. For objects in no container, which [`add`] cannot
402/// place: a response, a dependency.
403pub fn create<'a>(
404    files: &[File<'a>],
405    into: &str,
406    class: &str,
407    values: &[(&str, &str)],
408    random: &mut dyn FnMut() -> [u8; 16],
409) -> Result<Added<'a>, String> {
410    let reg = type_registry();
411    let file = files.iter().find(|f| f.name == into).ok_or_else(|| format!("no file {into}"))?;
412    // The class by the namespaces the file binds: CGMES's or NC's, whichever has it.
413    let found = file
414        .index
415        .namespaces
416        .iter()
417        .filter_map(|(_, ns)| reg.ns_table(ns)?.get(class).copied())
418        .next()
419        .ok_or_else(|| format!("{into} binds no namespace with a class {class}"))?;
420    let prefix = file.index.prefix_of(found.ns).ok_or("no prefix")?;
421    let id = fresh(files, &HashSet::new(), random);
422    let mut lines = vec![format!("<{prefix}:{} rdf:ID=\"{id}\">", found.local)];
423    // Its mRID as text: `IdentifiedObject.mRID`, or a class's own (`…Response.mRID`).
424    let mrid_key = reg.attrs(found).map(|a| a.id).find(|k| k.ends_with(".mRID"));
425    if let Some(key) = mrid_key.filter(|k| !values.iter().any(|(v, _)| v == k)) {
426        lines.push(format!("  {}", field_element(file, found, key, &id[1..])?));
427    }
428    for (key, value) in values {
429        lines.push(format!("  {}", field_element(file, found, key, value)?));
430    }
431    lines.push(format!("</{prefix}:{}>", found.local));
432    let edit = at_end(file, &lines)?;
433    let first = edit.range.start.line;
434    let select = Range::new(Position::new(first, 0), Position::new(first, 0));
435    Ok(Added { edits: vec![(file.name, vec![edit])], file: file.name.to_string(), select, id })
436}
437
438/// Objects copied: the edits, and each object's new mRID.
439pub struct Copied<'a> {
440    pub edits: Edits<'a>,
441    /// (original, copy), in the order given.
442    pub ids: Vec<(String, String)>,
443}
444
445/// Copy objects `ids` with new mRIDs (`_` and a UUID from `random`): every element writing each
446/// of them, in every file or only in `from`, its `rdf:ID` or `rdf:about`, its mRID field, and its
447/// references to the objects copied, rewritten to the copies; references to anything else stay.
448/// Each copy goes after its original, or with `into`, at the end of that file, which must bind
449/// the prefixes the copies use as their files do. `from` matters where two files define the same
450/// objects (a proposal and what was agreed of it): their copies would be one object written twice.
451pub fn copy<'a>(
452    files: &[File<'a>],
453    ids: &[&str],
454    from: Option<&str>,
455    into: Option<&str>,
456    random: &mut dyn FnMut() -> [u8; 16],
457) -> Result<Copied<'a>, String> {
458    let sources = |f: &&File| from.is_none_or(|n| f.name == n);
459    let target = match into {
460        Some(name) => Some(files.iter().find(|f| f.name == name).ok_or_else(|| format!("no file {name}"))?),
461        None => None,
462    };
463    let mut taken = HashSet::new();
464    let mut renamed: Vec<(String, String)> = Vec::new();
465    for id in ids {
466        if !files.iter().filter(sources).any(|f| f.index.elements.iter().any(|e| e.mrid == *id)) {
467            return Err(format!("no file {}writes `{id}`", from.map_or(String::new(), |n| format!("but {n} "))));
468        }
469        let new = fresh(files, &taken, random);
470        taken.insert(new.clone());
471        renamed.push((id.to_string(), new));
472    }
473    let to: HashMap<&str, &str> = renamed.iter().map(|(o, n)| (o.as_str(), n.as_str())).collect();
474    let mut changes: Edits<'a> = Vec::new();
475    let mut moved: Vec<String> = Vec::new();
476    for file in files.iter().filter(sources) {
477        let text = file.text;
478        let mut edits = Vec::new();
479        for el in file.index.elements.iter().filter(|e| to.contains_key(e.mrid.as_str())) {
480            if let Some(t) = target.filter(|t| t.name != file.name) {
481                // The copy's prefixes, bound as they are here.
482                let qnames = std::iter::once(&el.qname).chain(el.fields.iter().map(|f| &f.qname));
483                for q in qnames {
484                    let p = crate::index::prefix(q);
485                    if t.index.namespace(p) != file.index.namespace(p) {
486                        return Err(format!("{} binds `{p}` otherwise than {}", t.name, file.name));
487                    }
488                }
489            }
490            let block = file.lines_of(el.full);
491            let (start, end) = (file.lines.offset(text, block.start), file.lines.offset(text, block.end));
492            // Replacements within the block, by offset.
493            let mut swaps: Vec<(usize, usize, String)> = Vec::new();
494            // An mRID at the end of the value written at `r`.
495            let suffix = |r: Range, old: &str, new: &str| {
496                let at = file.lines.offset(text, r.end);
497                (at - old.len(), at, new.to_string())
498            };
499            let old = el.mrid.as_str();
500            let new = to[old];
501            if let Some(r) = el.id_range {
502                swaps.push(suffix(r, old, new));
503            }
504            for f in &el.fields {
505                if let Some((target_id, r)) = &f.resource
506                    && let Some(n) = to.get(target_id.as_str())
507                {
508                    swaps.push(suffix(*r, target_id, n));
509                }
510                if f.key().ends_with(".mRID")
511                    && let Some((value, r)) = file.field_text(f.head, f.full, &f.qname)
512                {
513                    let bare = |s: &str| s.strip_prefix('_').unwrap_or(s).to_string();
514                    let (vs, ve) = (file.lines.offset(text, r.start), file.lines.offset(text, r.end));
515                    if value.trim() == old {
516                        swaps.push((vs, ve, new.to_string()));
517                    } else if value.trim() == bare(old) {
518                        swaps.push((vs, ve, bare(new)));
519                    }
520                }
521            }
522            swaps.sort_by_key(|s| std::cmp::Reverse(s.0));
523            let mut copied = text[start..end].to_string();
524            for (s, e, with) in swaps {
525                copied.replace_range(s - start..e - start, &with);
526            }
527            if !copied.ends_with('\n') {
528                copied.push_str(if text.contains("\r\n") { "\r\n" } else { "\n" });
529            }
530            match target {
531                Some(_) => moved.push(copied),
532                None => edits.push(TextEdit::new(Range::new(block.end, block.end), copied)),
533            }
534        }
535        if !edits.is_empty() {
536            changes.push((file.name, edits));
537        }
538    }
539    if let Some(t) = target {
540        let root_end = t.text.rfind("</").ok_or("the file has no root end tag")?;
541        let line_start = t.text[..root_end].rfind('\n').map_or(0, |i| i + 1);
542        let at = t.lines.position(t.text, line_start);
543        let edit = TextEdit::new(Range::new(at, at), moved.concat());
544        match changes.iter_mut().find(|(n, _)| *n == t.name) {
545            Some((_, e)) => e.push(edit),
546            None => changes.push((t.name, vec![edit])),
547        }
548    }
549    Ok(Copied { edits: changes, ids: renamed })
550}
551
552/// An object a reference can name.
553pub struct Candidate {
554    pub id: String,
555    pub label: String,
556    pub class: &'static str,
557    /// Its containers' labels, as the outline shows them.
558    pub place: String,
559}
560
561impl Candidate {
562    /// The reference to it as written: `#_id`, or an IRI as it is.
563    pub fn reference(&self) -> String {
564        if self.id.contains(':') { self.id.clone() } else { format!("#{}", self.id) }
565    }
566}
567
568/// The objects field `key` of object `id` can name — of the class it ranges
569/// over, or below — at most `limit`, the likeliest first: those linked to
570/// the object, naming what it names with its other fields or named by it
571/// (a terminal's connectivity node, of its topological node; equipment's
572/// base voltage, its voltage level's); then those that share the most
573/// containers with it, by where they are or by where the objects are that
574/// name them with the same field (a line's base voltage is the one the
575/// equipment of its voltage level names); then the most named.
576/// Empty if `key` is not a reference of the object's class.
577pub fn candidates(indexes: &[&Index], tree: &Tree, id: &str, key: &str, limit: usize) -> Vec<Candidate> {
578    let reg = type_registry();
579    let class = indexes
580        .iter()
581        .flat_map(|ix| ix.elements.iter().filter(|e| e.mrid == id).map(move |e| (ix, e)))
582        .max_by_key(|(_, e)| e.id_kind == Some(IdKind::Id))
583        .and_then(|(ix, e)| ix.class_of(&e.qname));
584    let Some(attr) = class.and_then(|c| reg.attr(c, key)).filter(|a| a.kind == AttrKind::Association) else { return Vec::new() };
585    // What the object names with its other fields.
586    let own: HashSet<&str> = indexes
587        .iter()
588        .flat_map(|ix| ix.elements.iter().filter(|e| e.mrid == id))
589        .flat_map(|e| e.fields.iter().filter(|f| f.key() != key).filter_map(|f| f.resource.as_ref().map(|(t, _)| t.as_str())))
590        .filter(|t| !t.is_empty())
591        .collect();
592    let mut linked: HashSet<&str> = HashSet::new();
593    let mut found: HashMap<&str, (Option<&str>, &'static str)> = HashMap::new();
594    let mut named: HashMap<&str, Vec<&str>> = HashMap::new();
595    for ix in indexes {
596        for el in &ix.elements {
597            let targets = || el.fields.iter().filter_map(|f| f.resource.as_ref().map(|(t, _)| t.as_str()));
598            if own.contains(el.mrid.as_str()) {
599                linked.extend(targets());
600            } else if targets().any(|t| own.contains(t)) {
601                linked.insert(el.mrid.as_str());
602            }
603            for f in el.fields.iter().filter(|f| f.key() == key && el.mrid != id) {
604                if let Some((target, _)) = &f.resource {
605                    named.entry(target.as_str()).or_default().push(el.mrid.as_str());
606                }
607            }
608            if el.mrid.is_empty() || el.mrid == id {
609                continue;
610            }
611            let Some(c) = ix.class_of(&el.qname).filter(|c| reg.chain(c).iter().any(|a| a.local == attr.range)) else { continue };
612            let entry = found.entry(el.mrid.as_str()).or_insert((None, c.local));
613            if entry.0.is_none() {
614                entry.0 = el.name.as_deref().filter(|n| !n.is_empty());
615            }
616        }
617    }
618    let here = {
619        let mut chain = tree.chain(id);
620        chain.pop();
621        chain
622    };
623    let shared = |chain: &[u32]| here.iter().zip(chain).take_while(|(a, b)| a == b).count();
624    let mut ranked: Vec<(bool, usize, usize, String, &str, &'static str)> = found
625        .into_iter()
626        .map(|(c, (name, class))| {
627            let by = named.get(c).map_or(&[][..], Vec::as_slice);
628            let near = by.iter().map(|r| {
629                let mut chain = tree.chain(r);
630                chain.pop();
631                shared(&chain)
632            });
633            let score = near.chain(std::iter::once(shared(&tree.chain(c)))).max().unwrap_or(0);
634            (linked.contains(c), score, by.len(), name.unwrap_or(c).to_string(), c, class)
635        })
636        .collect();
637    ranked.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)).then(b.2.cmp(&a.2)).then_with(|| a.3.to_lowercase().cmp(&b.3.to_lowercase())));
638    ranked
639        .into_iter()
640        .take(limit)
641        .map(|(_, _, _, label, c, class)| Candidate { id: c.to_string(), label, class, place: tree.containers(c).join(" › ") })
642        .collect()
643}
644
645/// A class that can be added in an object, and the field naming it there.
646pub struct Addable {
647    pub class: &'static cimmodel::base::ClassDef,
648    pub key: &'static str,
649}
650
651/// The class of object `id` as the file defining it writes it.
652fn class_in(files: &[File], id: &str) -> Option<&'static cimmodel::base::ClassDef> {
653    let (file, el) = files
654        .iter()
655        .flat_map(|f| f.index.elements.iter().filter(|e| e.mrid == id).map(move |e| (f, e)))
656        .max_by_key(|(_, e)| e.id_kind == Some(IdKind::Id))?;
657    file.index.class_of(&el.qname)
658}
659
660/// The concrete classes of `parent`'s family whose objects the containment
661/// puts in it: the first of [`CONTAINED`] they declare that
662/// ranges over its class. Only classes of the profiles the set's files
663/// declare (all, if none declares one).
664pub fn addable(files: &[File], parent: &str) -> Vec<Addable> {
665    let reg = type_registry();
666    let Some(class) = class_in(files, parent) else { return Vec::new() };
667    let Some(schema) = reg.family_of(class.qualified).and_then(|f| reg.schema(f)) else { return Vec::new() };
668    let is = |range: &str| reg.chain(class).iter().any(|c| c.local == range);
669    let declared: HashSet<&str> = files.iter().flat_map(profiles).collect();
670    let mut out: Vec<Addable> = schema
671        .classes
672        .iter()
673        .filter(|c| c.concrete && (declared.is_empty() || c.origins.iter().any(|o| declared.contains(o))))
674        .filter_map(|c| {
675            let key = CONTAINED.iter().find_map(|k| reg.attr(c, k).filter(|a| a.used && a.kind == AttrKind::Association))?;
676            is(key.range).then_some(Addable { class: c, key: key.id })
677        })
678        .collect();
679    out.sort_by_key(|a| a.class.local);
680    out
681}
682
683/// A version 4 UUID from 16 random bytes, which the caller draws: the standard
684/// library has no randomness on every target this runs on.
685pub fn uuid(mut b: [u8; 16]) -> String {
686    b[6] = (b[6] & 0x0f) | 0x40;
687    b[8] = (b[8] & 0x3f) | 0x80;
688    let hex: String = b.iter().map(|x| format!("{x:02x}")).collect();
689    format!("{}-{}-{}-{}-{}", &hex[..8], &hex[8..12], &hex[12..16], &hex[16..20], &hex[20..])
690}
691
692/// An object added: the edits, and where its name (else its start tag) is.
693pub struct Added<'a> {
694    pub edits: Edits<'a>,
695    /// The file its element is in, by its name.
696    pub file: String,
697    pub select: Range,
698    pub id: String,
699}
700
701/// Add an object of `class` in `parent`, named `name` if given: an
702/// `rdf:ID`, its mRID, name and the field naming `parent`, in the file
703/// whose profile carries the class (the parent's own first), after the last
704/// of the parent's objects there, else after the parent, else at the end;
705/// and where the set has an SSH file and the class SSH attributes, an empty
706/// `rdf:about` there for them. What else it needs, validation asks for. Its
707/// mRID is `_` and a UUID from `random` ([`uuid`]), drawn again while the set
708/// has it.
709pub fn add<'a>(
710    files: &[File<'a>],
711    tree: &Tree,
712    parent: &str,
713    class: &str,
714    name: Option<&str>,
715    random: &mut dyn FnMut() -> [u8; 16],
716) -> Result<Added<'a>, String> {
717    let reg = type_registry();
718    let found = addable(files, parent);
719    let Addable { class, key } = found.into_iter().find(|a| a.class.local == class).ok_or_else(|| format!("a {class} cannot be added there"))?;
720    let fits = |f: &File| {
721        let declared = profiles(f);
722        declared.is_empty() || declared.iter().any(|p| class.origins.contains(p))
723    };
724    let defines = |f: &File, id: &str| f.index.elements.iter().any(|e| e.mrid == id && e.id_kind == Some(IdKind::Id));
725    let main = files
726        .iter()
727        .filter(|f| fits(f) && !profiles(f).contains(&"SSH"))
728        .max_by_key(|f| defines(f, parent))
729        .ok_or_else(|| format!("no file of the model set has a profile for {}", class.local))?;
730    let mut id = format!("_{}", uuid(random()));
731    while files.iter().any(|f| f.index.elements.iter().any(|e| e.mrid == id)) {
732        id = format!("_{}", uuid(random()));
733    }
734
735    let prefix = |f: &File, ns: &str| f.index.prefix_of(ns).map(str::to_string);
736    let tag = format!("{}:{}", prefix(main, class.ns).ok_or("the file binds no prefix to the class's namespace")?, class.local);
737    let field = |f: &File, key: &str| reg.attr(class, key).and_then(|a| Some((a, format!("{}:{}", prefix(f, a.ns)?, a.id))));
738    let carries = |f: &File, key: &str| {
739        let declared = profiles(f);
740        reg.attr(class, key).is_some_and(|a| declared.is_empty() || a.origins.iter().any(|o| declared.contains(o)))
741    };
742    let mut lines = vec![format!("<{tag} rdf:ID=\"{id}\">")];
743    let mut select_line = None;
744    if carries(main, "IdentifiedObject.mRID")
745        && let Some((_, t)) = field(main, "IdentifiedObject.mRID")
746    {
747        lines.push(format!("  <{t}>{}</{t}>", &id[1..]));
748    }
749    if let Some(name) = name.map(str::trim).filter(|n| !n.is_empty())
750        && let Some((_, t)) = field(main, "IdentifiedObject.name")
751    {
752        select_line = Some((lines.len(), t.len() + 4, name.encode_utf16().count()));
753        let escaped = name.replace('&', "&amp;").replace('<', "&lt;");
754        lines.push(format!("  <{t}>{escaped}</{t}>"));
755    }
756    let (_, container) = field(main, key).ok_or("the file binds no prefix to the field's namespace")?;
757    let target = if parent.contains(':') { parent.to_string() } else { format!("#{parent}") };
758    lines.push(format!("  <{container} rdf:resource=\"{target}\" />"));
759    lines.push(format!("</{tag}>"));
760
761    let mut changes: Edits<'a> = Vec::new();
762    let (at, line_no) = insertion(main, tree, parent, &lines)?;
763    let select = match select_line {
764        Some((l, col, len)) => {
765            let start = Position::new(line_no + l as u32, at.1 + col as u32);
766            Range::new(start, Position::new(start.line, start.character + len as u32))
767        }
768        None => Range::new(Position::new(line_no, at.1), Position::new(line_no, at.1)),
769    };
770    changes.push((main.name, vec![at.0]));
771    // Its steady-state part.
772    if class.origins.contains(&"SSH")
773        && let Some(ssh) = files.iter().find(|f| profiles(f).contains(&"SSH"))
774        && let Some(p) = prefix(ssh, class.ns)
775    {
776        let tag = format!("{p}:{}", class.local);
777        let ssh_lines = vec![format!("<{tag} rdf:about=\"#{id}\">"), format!("</{tag}>")];
778        let (edit, _) = insertion(ssh, tree, parent, &ssh_lines)?;
779        changes.push((ssh.name, vec![edit.0]));
780    }
781    Ok(Added { edits: changes, file: main.name.to_string(), select, id })
782}
783
784/// Where to insert `lines` (an element, unindented) in `file`: after the
785/// last element there of an object `parent` holds, else after `parent`'s,
786/// else before the root's end tag; indented as the elements are, in the
787/// file's line endings. The edit with the indent's width, and the line the
788/// element starts on.
789fn insertion(file: &File, tree: &Tree, parent: &str, lines: &[String]) -> Result<((TextEdit, u32), u32), String> {
790    let (text, li) = (file.text, file.lines);
791    let eol = if text.contains("\r\n") { "\r\n" } else { "\n" };
792    let siblings: HashSet<&str> = tree.children(parent).into_iter().collect();
793    let anchor = file.index.elements.iter().rev().find(|e| siblings.contains(e.mrid.as_str()))
794        .or_else(|| file.index.elements.iter().rev().find(|e| e.mrid == parent));
795    let (offset, indent) = match anchor {
796        Some(el) => {
797            let end = li.offset(text, el.full.end);
798            let line_end = text[end..].find('\n').map_or(text.len(), |i| end + i + 1);
799            let head = li.offset(text, el.head.start);
800            let line_start = text[..head].rfind('\n').map_or(0, |i| i + 1);
801            (line_end, text[line_start..head].to_string())
802        }
803        None => {
804            let root_end = text.rfind("</").ok_or("the file has no root end tag")?;
805            let line_start = text[..root_end].rfind('\n').map_or(0, |i| i + 1);
806            let indent = file.index.elements.last().map_or("  ".to_string(), |el| {
807                let head = li.offset(text, el.head.start);
808                text[text[..head].rfind('\n').map_or(0, |i| i + 1)..head].to_string()
809            });
810            (line_start, indent)
811        }
812    };
813    // An anchor ending the file without a newline: start a line first.
814    let lead = if offset == text.len() && !text.ends_with('\n') { eol } else { "" };
815    let body: String = lines.iter().map(|l| format!("{indent}{l}{eol}")).collect();
816    let at = li.position(text, offset);
817    let first = if lead.is_empty() { at.line } else { at.line + 1 };
818    Ok(((TextEdit::new(Range::new(at, at), format!("{lead}{body}")), indent.encode_utf16().count() as u32), first))
819}
820
821/// A fix for a reference to nothing (`rdf:resource="#"`) or to an object the
822/// set lacks: name one of the likeliest objects instead.
823pub struct ReferenceFix {
824    pub key: String,
825    /// The file it is in, by its name.
826    pub file: String,
827    pub edit: TextEdit,
828    pub title: String,
829    /// It names nothing; else something the set does not have.
830    pub empty: bool,
831}
832
833/// The fixes for object `id`'s references to nothing or to objects the set
834/// lacks, in every file that writes it, or only the field at `at`: each the
835/// five likeliest objects ([`candidates`]); `at` names a file and a place in
836/// it. An enumeration value is not a reference to an object, so it has none.
837pub fn reference_fixes(files: &[File], tree: &Tree, id: &str, at: Option<(&str, Position)>) -> Vec<ReferenceFix> {
838    let sites: Vec<(&File, &crate::index::Field, &str, Range)> = files
839        .iter()
840        .filter(|f| at.is_none_or(|(n, _)| f.name == n))
841        .flat_map(|f| f.index.elements.iter().filter(|e| e.mrid == id).map(move |e| (f, e)))
842        .flat_map(|(f, e)| e.fields.iter().map(move |x| (f, x)))
843        .filter(|(_, x)| at.is_none_or(|(_, pos)| contains(x.full, pos)))
844        .filter_map(|(f, x)| x.resource.as_ref().map(|(t, r)| (f, x, t.as_str(), *r)))
845        .collect();
846    if sites.is_empty() {
847        return Vec::new();
848    }
849    let known: HashSet<&str> = files.iter().flat_map(|f| f.index.elements.iter().map(|e| e.mrid.as_str())).collect();
850    let indexes: Vec<&Index> = files.iter().map(|f| f.index).collect();
851    let mut out = Vec::new();
852    for (file, field, target, value) in sites {
853        if !target.is_empty() && known.contains(target) {
854            continue;
855        }
856        for c in candidates(&indexes, tree, id, field.key(), 5) {
857            let place = if c.place.is_empty() { String::new() } else { format!(" in {}", c.place) };
858            out.push(ReferenceFix {
859                key: field.key().to_string(),
860                file: file.name.to_string(),
861                edit: TextEdit::new(value, c.reference()),
862                title: format!("Set {} to {} {}{place}", field.key(), c.class, c.label),
863                empty: target.is_empty(),
864            });
865        }
866    }
867    out
868}
869
870/// The objects that refer to object `id`, and by which field, as the files
871/// write them: (referrer, field), each once.
872pub fn referrers<'a>(files: &[File<'a>], id: &str) -> Vec<(&'a str, &'a str)> {
873    let mut out: Vec<(&str, &str)> = files
874        .iter()
875        .flat_map(|f| f.index.elements.iter())
876        .flat_map(|e| e.fields.iter().filter(|x| x.resource.as_ref().is_some_and(|(t, _)| t == id)).map(move |x| (e.mrid.as_str(), x.key())))
877        .filter(|(r, _)| !r.is_empty() && *r != id)
878        .collect();
879    out.sort_unstable();
880    out.dedup();
881    out
882}
883
884/// How an object is named in a title: its class and name, else mRID.
885pub fn describe(files: &[File], id: &str) -> String {
886    let el = files.iter().flat_map(|f| &f.index.elements).filter(|e| e.mrid == id).max_by_key(|e| e.id_kind == Some(IdKind::Id));
887    match el {
888        Some(el) => format!("{} {}", local(&el.qname), el.name.as_deref().filter(|n| !n.is_empty()).unwrap_or(id)),
889        None => id.to_string(),
890    }
891}
892
893#[cfg(test)]
894mod tests {
895    use super::*;
896
897    fn micro_grid() -> std::path::PathBuf {
898        std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
899            .join("../CGMES-Test-Configurations/v3.0/MicroGrid/MicroGid-BaseCase/MicroGrid-BaseCase-Merged")
900    }
901
902    #[test]
903    fn a_uuid_is_version_4() {
904        let id = uuid([0xff; 16]);
905        assert_eq!(id.len(), 36);
906        assert_eq!(&id[14..15], "4");
907        assert!(matches!(&id[19..20], "8" | "9" | "a" | "b"), "{id}");
908    }
909
910    const EQ: &str = r##"<rdf:RDF xmlns:cim="http://iec.ch/TC57/CIM100#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
911  <cim:Breaker rdf:ID="_b1">
912    <cim:IdentifiedObject.mRID>b1</cim:IdentifiedObject.mRID>
913    <cim:IdentifiedObject.name>B1</cim:IdentifiedObject.name>
914  </cim:Breaker>
915  <cim:Terminal rdf:ID="_t1">
916    <cim:Terminal.ConductingEquipment rdf:resource="#_b1" />
917    <cim:IdentifiedObject.name>T1</cim:IdentifiedObject.name>
918  </cim:Terminal>
919</rdf:RDF>"##;
920    const SSH: &str = r##"<rdf:RDF xmlns:cim="http://iec.ch/TC57/CIM100#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
921  <cim:Breaker rdf:about="#_b1">
922    <cim:Switch.open>false</cim:Switch.open>
923  </cim:Breaker>
924</rdf:RDF>"##;
925
926    fn apply(text: &str, edits: Vec<TextEdit>) -> String {
927        crate::text::apply(text, &edits)
928    }
929
930    /// The edits of the file `name`.
931    fn of<'a>(edits: &Edits<'a>, name: &str) -> Vec<TextEdit> {
932        edits.iter().find(|(n, _)| *n == name).map(|(_, e)| e.clone()).unwrap_or_default()
933    }
934
935    fn with_files<R>(f: impl FnOnce(&[File]) -> R) -> R {
936        let names = ["EQ.xml", "SSH.xml"];
937        let texts = [EQ, SSH];
938        let lines: Vec<LineIndex> = texts.iter().map(|t| LineIndex::new(t)).collect();
939        let indexes: Vec<Index> = texts.iter().map(|t| Index::build(t)).collect();
940        let files: Vec<File> = (0..2).map(|i| File { name: names[i], text: texts[i], lines: &lines[i], index: &indexes[i] }).collect();
941        f(&files)
942    }
943
944    #[test]
945    fn renames_an_mrid_everywhere() {
946        with_files(|files| {
947            // On the reference, and on the start tag.
948            let (r, old) = prepare_rename(files, "EQ.xml", Position::new(6, 55)).unwrap();
949            assert_eq!((old.as_str(), r), ("_b1", Range::new(Position::new(6, 53), Position::new(6, 56))));
950            assert_eq!(prepare_rename(files, "SSH.xml", Position::new(1, 4)).unwrap().1, "_b1");
951            assert!(prepare_rename(files, "EQ.xml", Position::new(2, 10)).is_none());
952
953            let changes = rename(files, "_b1", "_b2").unwrap();
954            let eq = apply(EQ, of(&changes, "EQ.xml"));
955            assert!(eq.contains(r#"rdf:ID="_b2""#) && eq.contains(">b2</") && eq.contains(r##"rdf:resource="#_b2""##), "{eq}");
956            assert!(!eq.contains("b1"), "{eq}");
957            assert_eq!(apply(SSH, of(&changes, "SSH.xml")), SSH.replace("#_b1", "#_b2"));
958
959            assert!(rename(files, "_b1", "_t1").is_err());
960            assert!(rename(files, "_b1", "a b").is_err());
961            assert!(rename(files, "_b1", "1b").is_err());
962        });
963    }
964
965    #[test]
966    fn adds_a_missing_field_where_its_profile_is() {
967        let header = |p: &str| format!(r#"  <md:FullModel rdf:about="urn:uuid:{p}">
968    <md:Model.profile>http://iec.ch/TC57/ns/CIM/{p}/3.0</md:Model.profile>
969  </md:FullModel>
970"#);
971        let with_header = |text: &str, p: &str| {
972            text.replacen(r#"xmlns:rdf"#, r#"xmlns:md="http://iec.ch/TC57/61970-552/ModelDescription/1#" xmlns:rdf"#, 1)
973                .replacen(">\n", &format!(">\n{}", header(p)), 1)
974        };
975        let texts = [with_header(EQ, "CoreEquipment-EU"), with_header(SSH, "SteadyStateHypothesis-EU")];
976        let names = ["EQ.xml", "SSH.xml"];
977        let lines: Vec<LineIndex> = texts.iter().map(|t| LineIndex::new(t)).collect();
978        let indexes: Vec<Index> = texts.iter().map(|t| Index::build(t)).collect();
979        let files: Vec<File> = (0..2).map(|i| File { name: names[i], text: &texts[i], lines: &lines[i], index: &indexes[i] }).collect();
980        let added = |id: &str, key: &str| {
981            let a = add_missing(&files, names[0], id, key)?;
982            let i = names.iter().position(|n| *n == a.file).unwrap();
983            let out = apply(&texts[i], vec![a.edit.clone()]);
984            let selected = apply(&out, vec![TextEdit::new(a.value, "|".into())]);
985            Some((i, out, selected))
986        };
987
988        // An SSH attribute goes to the SSH file, though asked from the EQ one.
989        let (i, out, selected) = added("_b1", "Equipment.inService").unwrap();
990        assert_eq!(i, 1);
991        assert!(out.contains("<cim:Switch.open>false</cim:Switch.open>\n    <cim:Equipment.inService>false</cim:Equipment.inService>\n  </cim:Breaker>"), "{out}");
992        assert!(selected.contains("<cim:Equipment.inService>|</cim:Equipment.inService>"), "{selected}");
993        // An EQ one to the EQ file; a reference left to fill in, an enumeration its first value.
994        let (i, _, selected) = added("_t1", "Terminal.ConnectivityNode").unwrap();
995        assert_eq!(i, 0);
996        assert!(selected.contains(r##"<cim:Terminal.ConnectivityNode rdf:resource="#|" />"##), "{selected}");
997        let (_, out, _) = added("_t1", "Terminal.phases").unwrap();
998        assert!(out.contains(r#"<cim:Terminal.phases rdf:resource="http://iec.ch/TC57/CIM100#PhaseCode."#), "{out}");
999        // Written already, or not the class's.
1000        assert!(added("_b1", "Switch.open").is_none());
1001        assert!(added("_b1", "ACLineSegment.r").is_none());
1002    }
1003
1004    #[test]
1005    fn sets_and_removes_a_field_wherever_it_is_written() {
1006        with_files(|files| {
1007            // A literal, escaped; written in the SSH file.
1008            let set = set_field(files, "EQ.xml", "_b1", "Switch.open", "true").unwrap();
1009            assert_eq!(apply(SSH, of(&set, "SSH.xml")), SSH.replace(">false<", ">true<"));
1010            let named = set_field(files, "EQ.xml", "_b1", "IdentifiedObject.name", "B & 1").unwrap();
1011            assert!(apply(EQ, of(&named, "EQ.xml")).contains("<cim:IdentifiedObject.name>B &amp; 1</cim:IdentifiedObject.name>"));
1012            // A reference, to an mRID.
1013            let to = set_field(files, "EQ.xml", "_t1", "Terminal.ConductingEquipment", "_b2").unwrap();
1014            assert!(apply(EQ, of(&to, "EQ.xml")).contains(r##"<cim:Terminal.ConductingEquipment rdf:resource="#_b2" />"##));
1015            // Written nowhere: added, with the value given.
1016            let added = set_field(files, "EQ.xml", "_t1", "Terminal.phases", "ABC").unwrap();
1017            assert!(apply(EQ, of(&added, "EQ.xml")).contains(r#"<cim:Terminal.phases rdf:resource="http://iec.ch/TC57/CIM100#PhaseCode.ABC" />"#));
1018            assert!(set_field(files, "EQ.xml", "_b1", "ACLineSegment.r", "1").is_err());
1019
1020            let removed = remove_field(files, "_t1", "Terminal.ConductingEquipment");
1021            let eq = apply(EQ, of(&removed, "EQ.xml"));
1022            assert!(!eq.contains("ConductingEquipment") && eq.contains("<cim:Terminal rdf:ID=\"_t1\">\n    <cim:IdentifiedObject.name>T1"), "{eq}");
1023        });
1024    }
1025
1026    fn counting() -> impl FnMut() -> [u8; 16] {
1027        let mut n = 0u8;
1028        move || {
1029            n += 1;
1030            [n; 16]
1031        }
1032    }
1033
1034    #[test]
1035    fn copies_objects_with_new_mrids_and_their_references_among_them() {
1036        with_files(|files| {
1037            let mut random = counting();
1038            let copied = copy(files, &["_b1", "_t1"], None, None, &mut random).unwrap();
1039            let (b2, t2) = (format!("_{}", uuid([1; 16])), format!("_{}", uuid([2; 16])));
1040            assert_eq!(copied.ids, [("_b1".to_string(), b2.clone()), ("_t1".to_string(), t2.clone())]);
1041            let eq = apply(EQ, of(&copied.edits, "EQ.xml"));
1042            // The originals stay; the copies follow them, naming each other.
1043            assert!(eq.contains(r#"<cim:Breaker rdf:ID="_b1">"#) && eq.contains(&format!(r#"<cim:Breaker rdf:ID="{b2}">"#)), "{eq}");
1044            assert!(eq.contains(&format!("<cim:IdentifiedObject.mRID>{}</cim:IdentifiedObject.mRID>", &b2[1..])), "{eq}");
1045            assert!(eq.contains(&format!(r##"<cim:Terminal.ConductingEquipment rdf:resource="#{b2}" />"##)), "{eq}");
1046            assert_eq!(eq.matches(r##"rdf:resource="#_b1""##).count(), 1);
1047            let ssh = apply(SSH, of(&copied.edits, "SSH.xml"));
1048            assert!(ssh.contains(&format!(r##"<cim:Breaker rdf:about="#{b2}">"##)), "{ssh}");
1049            // Only the terminal: its reference to the breaker stays.
1050            let alone = copy(files, &["_t1"], None, None, &mut random).unwrap();
1051            assert_eq!(apply(EQ, of(&alone.edits, "EQ.xml")).matches(r##"rdf:resource="#_b1""##).count(), 2);
1052            // From one file, into another: the breaker's SSH part is not copied.
1053            let only = copy(files, &["_b1"], Some("EQ.xml"), None, &mut random).unwrap();
1054            assert_eq!(only.edits.len(), 1, "EQ only");
1055            let moved = copy(files, &["_t1"], None, Some("SSH.xml"), &mut random).unwrap();
1056            let ssh = apply(SSH, of(&moved.edits, "SSH.xml"));
1057            assert!(ssh.contains(&format!(r#"<cim:Terminal rdf:ID="{}">"#, moved.ids[0].1)) && ssh.ends_with("</rdf:RDF>"), "{ssh}");
1058            assert!(copy(files, &["_nothing"], None, None, &mut random).is_err());
1059            assert!(copy(files, &["_t1"], Some("SSH.xml"), None, &mut random).is_err());
1060        });
1061    }
1062
1063    #[test]
1064    fn creates_an_object_of_any_class_with_its_values() {
1065        with_files(|files| {
1066            let created = create(files, "EQ.xml", "Breaker", &[("IdentifiedObject.name", "B9"), ("Switch.normalOpen", "true")], &mut counting()).unwrap();
1067            let eq = apply(EQ, of(&created.edits, "EQ.xml"));
1068            let id = &created.id;
1069            assert!(eq.contains(&format!("  <cim:Breaker rdf:ID=\"{id}\">\n    <cim:IdentifiedObject.mRID>{}</cim:IdentifiedObject.mRID>\n    <cim:IdentifiedObject.name>B9</cim:IdentifiedObject.name>\n    <cim:Switch.normalOpen>true</cim:Switch.normalOpen>\n  </cim:Breaker>\n</rdf:RDF>", &id[1..])), "{eq}");
1070            assert!(create(files, "EQ.xml", "NoSuchClass", &[], &mut counting()).is_err());
1071            assert!(create(files, "EQ.xml", "Breaker", &[("ACLineSegment.r", "1")], &mut counting()).is_err());
1072        });
1073    }
1074
1075    #[test]
1076    fn lists_what_refers_to_an_object() {
1077        with_files(|files| {
1078            assert_eq!(referrers(files, "_b1"), [("_t1", "Terminal.ConductingEquipment")]);
1079            assert!(referrers(files, "_t1").is_empty());
1080        });
1081    }
1082
1083    #[test]
1084    fn deletes_an_object_from_every_file() {
1085        with_files(|files| {
1086            let d = delete(files, &HashSet::from(["_b1"]));
1087            assert_eq!((d.objects, d.references), (1, 1));
1088            let eq = apply(EQ, of(&d.edits, "EQ.xml"));
1089            assert!(!eq.contains("Breaker") && !eq.contains("ConductingEquipment") && eq.contains("<cim:Terminal rdf:ID=\"_t1\">\n    <cim:IdentifiedObject.name>T1"), "{eq}");
1090            assert!(!apply(SSH, of(&d.edits, "SSH.xml")).contains("Breaker"));
1091        });
1092    }
1093
1094    /// On MicroGrid, the object each reference names is among the
1095    /// candidates offered for it, mostly first.
1096    #[test]
1097    fn candidates_rank_what_the_data_names() {
1098        let read = crate::testing::collect(&micro_grid());
1099        let set = crate::testing::validate(&read);
1100        let built: Vec<Index> = read.iter().map(|(_, t)| Index::build(t)).collect();
1101        let indexes: Vec<&Index> = built.iter().collect();
1102        let mut stats: HashMap<&str, (usize, usize, usize)> = HashMap::new();
1103        for ix in &indexes {
1104            for el in &ix.elements {
1105                for f in &el.fields {
1106                    let key = f.key();
1107                    let Some((target, _)) = &f.resource else { continue };
1108                    // Not the containment's own fields: the object is where they put it.
1109                    if !["ConductingEquipment.BaseVoltage", "Terminal.ConnectivityNode", "Terminal.TopologicalNode", "RegulatingControl.Terminal"].contains(&key) {
1110                        continue;
1111                    }
1112                    let c = candidates(&indexes, &set.tree, &el.mrid, key, 5);
1113                    let s = stats.entry(key).or_default();
1114                    s.0 += 1;
1115                    if c.first().is_some_and(|c| c.id == *target) { s.1 += 1 }
1116                    if c.iter().any(|c| c.id == *target) { s.2 += 1 }
1117                }
1118            }
1119        }
1120        for (key, (n, first, top5)) in &stats {
1121            eprintln!("{key}: {n} references, first {first}, top 5 {top5}");
1122        }
1123        // Linked through the topological node: always first. A base voltage:
1124        // a line's, among its sub-region's, not always.
1125        assert_eq!(stats["Terminal.ConnectivityNode"], (73, 73, 73));
1126        assert_eq!(stats["Terminal.TopologicalNode"], (73, 73, 73));
1127        assert_eq!(stats["RegulatingControl.Terminal"], (7, 7, 7));
1128        assert_eq!(stats["ConductingEquipment.BaseVoltage"], (23, 20, 23));
1129    }
1130
1131    /// On MicroGrid: what a voltage level and a transformer can hold; a breaker
1132    /// added in a voltage level, in EQ with an SSH part, which validates
1133    /// with findings for what it lacks and sits in the voltage level.
1134    #[test]
1135    fn adds_an_object_in_a_container() {
1136        let read = crate::testing::collect(&micro_grid());
1137        let set = crate::testing::validate(&read);
1138        let names: Vec<String> = read.iter().map(|(p, _)| p.to_string_lossy().into_owned()).collect();
1139        let lines: Vec<LineIndex> = read.iter().map(|(_, t)| LineIndex::new(t)).collect();
1140        let indexes: Vec<Index> = read.iter().map(|(_, t)| Index::build(t)).collect();
1141        let files: Vec<File> = (0..read.len()).map(|i| File { name: &names[i], text: &read[i].1, lines: &lines[i], index: &indexes[i] }).collect();
1142        let find = |class: &str, name: &str| indexes.iter().flat_map(|ix| &ix.elements)
1143            .find(|e| local(&e.qname) == class && e.name.as_deref() == Some(name)).unwrap().mrid.clone();
1144        let vl = find("VoltageLevel", "110.0");
1145        let classes: Vec<&str> = addable(&files, &vl).iter().map(|a| a.class.local).collect();
1146        for c in ["Breaker", "Bay", "ConnectivityNode", "LinearShuntCompensator"] {
1147            assert!(classes.contains(&c), "{classes:?}");
1148        }
1149        assert!(!classes.contains(&"Terminal"), "{classes:?}");
1150        let transformer = find("PowerTransformer", "BE-TR2_1");
1151        let classes: Vec<&str> = addable(&files, &transformer).iter().map(|a| a.class.local).collect();
1152        assert!(classes.contains(&"Terminal") && classes.contains(&"PowerTransformerEnd"), "{classes:?}");
1153
1154        let mut draws = 0u8;
1155        let mut random = || {
1156            draws += 1;
1157            [draws; 16]
1158        };
1159        let added = add(&files, &set.tree, &vl, "Breaker", Some("B-new"), &mut random).unwrap();
1160        assert_eq!(added.edits.len(), 2, "EQ and SSH");
1161        assert_eq!(added.id, format!("_{}", uuid([1; 16])));
1162        let edited: Vec<(std::path::PathBuf, std::sync::Arc<str>)> = read.iter().enumerate().map(|(i, (p, t))| {
1163            let e = of(&added.edits, &names[i]);
1164            (p.clone(), std::sync::Arc::from(if e.is_empty() { t.to_string() } else { apply(t, e) }))
1165        }).collect();
1166        let main = names.iter().position(|n| *n == added.file).unwrap();
1167        assert!(edited[main].0.to_string_lossy().contains("_EQ_"));
1168        let text = &edited[main].1;
1169        let selected = apply(text, vec![TextEdit::new(added.select, "|".into())]);
1170        assert!(selected.contains("<cim:IdentifiedObject.name>|</cim:IdentifiedObject.name>"), "the name is selected");
1171
1172        let set2 = crate::testing::validate(&edited);
1173        assert_eq!(set2.tree.containers(&added.id), ["PP_Brussels", "110.0"]);
1174        let ssh = edited.iter().find(|(p, _)| p.to_string_lossy().contains("_BE_SSH_")).unwrap();
1175        assert!(ssh.1.contains(&format!("rdf:about=\"#{}\"", added.id)));
1176    }
1177}
1178