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