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 schematic;
20pub mod single_line;
21pub mod state;
22pub mod text;
23pub mod topology;
24pub mod tree;
25
26/// Where a set's objects are written, which only the caller of a view knows:
27/// a language server has ranges in documents, a page only file names.
28pub trait Locations {
29    /// Where the object `id` is written, in whatever form the view's client
30    /// reads, `null` if the set does not write it.
31    fn location(&self, id: &str) -> Value;
32    /// The set's files, in that same form.
33    fn files(&self) -> Vec<Value>;
34}
35
36/// The mRID in a reference or an id as written: the text after the last `#`.
37pub fn mrid_of(value: &str) -> &str {
38    value.rsplit_once('#').map_or(value, |(_, f)| f)
39}
40
41/// A model set as the tests need it: files read, validated and located.
42#[cfg(test)]
43pub(crate) mod testing {
44    use std::collections::HashMap;
45    use std::path::{Path, PathBuf};
46    use std::sync::Arc;
47
48    use cimmodel::CimDataset;
49    use serde_json::{Value, json};
50
51    use crate::Locations;
52    use crate::grid::{self, Grid, Model};
53    use crate::tree::{self, Tree};
54
55    /// The CIM files of `dir`, in name order.
56    pub fn collect(dir: &Path) -> Vec<(PathBuf, Arc<str>)> {
57        let mut paths: Vec<PathBuf> = std::fs::read_dir(dir)
58            .map(|d| d.flatten().map(|e| e.path()).collect())
59            .unwrap_or_default();
60        paths.sort();
61        paths
62            .into_iter()
63            .filter_map(|p| {
64                let text = std::fs::read_to_string(&p).ok()?;
65                cimmodel::decode::is_cim(&text).then(|| (p, Arc::from(text)))
66            })
67            .collect()
68    }
69
70    pub struct Set {
71        pub grid: Grid,
72        pub tree: Tree,
73        files: Vec<String>,
74        /// mRID → the file of its `rdf:ID`, else of its first `rdf:about`.
75        defs: HashMap<String, (usize, bool)>,
76    }
77
78    impl Locations for Set {
79        fn location(&self, id: &str) -> Value {
80            match self.defs.get(id) {
81                Some(&(f, _)) => json!({ "uri": self.files[f] }),
82                None => Value::Null,
83            }
84        }
85        fn files(&self) -> Vec<Value> {
86            self.files.iter().map(|f| json!(f)).collect()
87        }
88    }
89
90    /// `files` as one model set, under the configuration `cimox validate
91    /// --common --quality` uses.
92    pub fn validate(files: &[(PathBuf, Arc<str>)]) -> Set {
93        let datasets: Vec<CimDataset> = files.iter().map(|(_, t)| CimDataset::decode_str(t).unwrap()).collect();
94        let mut defs: HashMap<String, (usize, bool)> = HashMap::new();
95        for (f, ds) in datasets.iter().enumerate() {
96            for (id, el) in &ds.entries {
97                let slot = defs.entry(id.to_string()).or_insert((f, el.defined()));
98                if el.defined() && !slot.1 {
99                    *slot = (f, true);
100                }
101            }
102        }
103        let cfg = cimvalidation::combined_config(&datasets, None, None, true, true, Vec::new());
104        let model = Model::new(&datasets);
105        let (mut grid, mut tree) = (grid::build(&model), tree::build(&model));
106        let found = cimvalidation::validate_files_traced(datasets, &cfg);
107        grid.add_findings(&found);
108        tree.add_findings(&found);
109        let files = files.iter().map(|(p, _)| p.to_string_lossy().into_owned()).collect();
110        Set { grid, tree, files, defs }
111    }
112}