Skip to main content

cimview/
lib.rs

1//! A model set as views, for whatever draws them: its grid at substation
2//! level ([`grid`], laid out by [`layout`]) and its objects as a tree
3//! ([`tree`]), with validation's findings counted on each. `cimlsp` serves
4//! them to the VS Code extension. Runs on wasm32-unknown-unknown too.
5//!
6//! The files themselves, as text: where each object and field is written
7//! ([`index`], in [`text`]'s positions), and edits to them across a set
8//! ([`edit`]): renaming, deleting, adding objects and fields.
9//!
10//! The views answer in JSON. Where an object is written is not in the data:
11//! the caller says, through [`Locations`].
12
13use serde_json::Value;
14
15pub mod edit;
16pub mod grid;
17pub mod index;
18pub mod layout;
19pub mod text;
20pub mod tree;
21
22/// Where a set's objects are written, which only the caller of a view knows:
23/// a language server has ranges in documents, a page only file names.
24pub trait Locations {
25    /// Where the object `id` is written, in whatever form the view's client
26    /// reads, `null` if the set does not write it.
27    fn location(&self, id: &str) -> Value;
28    /// The set's files, in that same form.
29    fn files(&self) -> Vec<Value>;
30}
31
32/// The mRID in a reference or an id as written: the text after the last `#`.
33pub fn mrid_of(value: &str) -> &str {
34    value.rsplit_once('#').map_or(value, |(_, f)| f)
35}
36
37/// A model set as the tests need it: files read, validated and located.
38#[cfg(test)]
39pub(crate) mod testing {
40    use std::collections::HashMap;
41    use std::path::{Path, PathBuf};
42    use std::sync::Arc;
43
44    use cimmodel::CimDataset;
45    use serde_json::{Value, json};
46
47    use crate::Locations;
48    use crate::grid::{self, Grid, Model};
49    use crate::tree::{self, Tree};
50
51    /// The CIM files of `dir`, in name order.
52    pub fn collect(dir: &Path) -> Vec<(PathBuf, Arc<str>)> {
53        let mut paths: Vec<PathBuf> = std::fs::read_dir(dir)
54            .map(|d| d.flatten().map(|e| e.path()).collect())
55            .unwrap_or_default();
56        paths.sort();
57        paths
58            .into_iter()
59            .filter_map(|p| {
60                let text = std::fs::read_to_string(&p).ok()?;
61                cimmodel::decode::is_cim(&text).then(|| (p, Arc::from(text)))
62            })
63            .collect()
64    }
65
66    pub struct Set {
67        pub grid: Grid,
68        pub tree: Tree,
69        files: Vec<String>,
70        /// mRID → the file of its `rdf:ID`, else of its first `rdf:about`.
71        defs: HashMap<String, (usize, bool)>,
72    }
73
74    impl Locations for Set {
75        fn location(&self, id: &str) -> Value {
76            match self.defs.get(id) {
77                Some(&(f, _)) => json!({ "uri": self.files[f] }),
78                None => Value::Null,
79            }
80        }
81        fn files(&self) -> Vec<Value> {
82            self.files.iter().map(|f| json!(f)).collect()
83        }
84    }
85
86    /// `files` as one model set, under the configuration `cimcli validate
87    /// --common --quality` uses.
88    pub fn validate(files: &[(PathBuf, Arc<str>)]) -> Set {
89        let datasets: Vec<CimDataset> = files.iter().map(|(_, t)| CimDataset::decode_str(t).unwrap()).collect();
90        let mut defs: HashMap<String, (usize, bool)> = HashMap::new();
91        for (f, ds) in datasets.iter().enumerate() {
92            for (id, el) in &ds.entries {
93                let slot = defs.entry(id.to_string()).or_insert((f, el.defined()));
94                if el.defined() && !slot.1 {
95                    *slot = (f, true);
96                }
97            }
98        }
99        let cfg = cimvalidation::combined_config(&datasets, None, None, true, true, Vec::new());
100        let model = Model::new(&datasets);
101        let (mut grid, mut tree) = (grid::build(&model), tree::build(&model));
102        let found = cimvalidation::validate_files_traced(datasets, &cfg);
103        grid.add_findings(&found);
104        tree.add_findings(&found);
105        let files = files.iter().map(|(p, _)| p.to_string_lossy().into_owned()).collect();
106        Set { grid, tree, files, defs }
107    }
108}