Skip to main content

predsync_compiler/
check.rs

1//! Receiver schema-set collision checks and deterministic table output.
2
3use std::{
4    collections::{BTreeMap, BTreeSet, btree_map::Entry},
5    fmt, fs,
6    path::{Path, PathBuf},
7    string::String,
8    vec::Vec,
9};
10
11/// One row of the printed message-ID table.
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct CheckRow {
14    pub qualified_name: String,
15    pub id: u8,
16    pub sets: Vec<String>,
17}
18
19/// The full deterministic report for all checked sets.
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct CheckReport {
22    pub rows: Vec<CheckRow>,
23}
24
25/// A collision, parse failure or cross-set ID disagreement.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub enum CheckError {
28    Io(String),
29    Parse {
30        path: PathBuf,
31        error: String,
32    },
33    Collision {
34        set: String,
35        id: u8,
36        left: String,
37        right: String,
38    },
39    DuplicateMessage {
40        set: String,
41        name: String,
42    },
43    InconsistentId {
44        name: String,
45        first: u8,
46        first_set: String,
47        second: u8,
48        second_set: String,
49    },
50}
51
52impl fmt::Display for CheckError {
53    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54        match self {
55            Self::Io(message) => write!(f, "I/O error: {message}"),
56            Self::Parse { path, error } => {
57                write!(f, "{}: {error}", path.display())
58            }
59            Self::Collision {
60                set,
61                id,
62                left,
63                right,
64            } => write!(
65                f,
66                "set {set}: message ID {id} is used by both {left} and {right}"
67            ),
68            Self::DuplicateMessage { set, name } => {
69                write!(f, "set {set}: message {name} is defined more than once")
70            }
71            Self::InconsistentId {
72                name,
73                first,
74                first_set,
75                second,
76                second_set,
77            } => write!(
78                f,
79                "message {name} has ID {first} in set {first_set} but ID {second} in set {second_set}"
80            ),
81        }
82    }
83}
84
85impl std::error::Error for CheckError {}
86
87/// Parse every `--set` path and validate IDs within and across sets.
88pub fn check_sets(paths: &[PathBuf]) -> Result<CheckReport, CheckError> {
89    let mut by_name: BTreeMap<String, (u8, BTreeSet<String>)> = BTreeMap::new();
90
91    for set_path in paths {
92        let label = set_label(set_path);
93        let mut ids: BTreeMap<u8, String> = BTreeMap::new();
94        for file in yaml_files(set_path)? {
95            let source = fs::read_to_string(&file)
96                .map_err(|error| CheckError::Io(format!("{}: {error}", file.display())))?;
97            let parsed = crate::parse_schema(&source).map_err(|error| CheckError::Parse {
98                path: file.clone(),
99                error: error.to_string(),
100            })?;
101            for message in parsed.set.messages {
102                let name = message.qualified_name();
103                match ids.entry(message.id) {
104                    Entry::Occupied(entry) => {
105                        let other = entry.get();
106                        return Err(if other == &name {
107                            CheckError::DuplicateMessage { set: label, name }
108                        } else {
109                            CheckError::Collision {
110                                set: label,
111                                id: message.id,
112                                left: other.clone(),
113                                right: name,
114                            }
115                        });
116                    }
117                    Entry::Vacant(entry) => {
118                        entry.insert(name.clone());
119                    }
120                }
121
122                match by_name.entry(name.clone()) {
123                    Entry::Occupied(mut entry) => {
124                        let (id, sets) = entry.get_mut();
125                        if *id != message.id {
126                            return Err(CheckError::InconsistentId {
127                                name: name.clone(),
128                                first: *id,
129                                first_set: sets.iter().next().cloned().unwrap_or_default(),
130                                second: message.id,
131                                second_set: label,
132                            });
133                        }
134                        sets.insert(label.clone());
135                    }
136                    Entry::Vacant(entry) => {
137                        let mut sets = BTreeSet::new();
138                        sets.insert(label.clone());
139                        entry.insert((message.id, sets));
140                    }
141                }
142            }
143        }
144    }
145
146    let mut rows = Vec::new();
147    for (qualified_name, (id, sets)) in by_name {
148        for set in sets {
149            rows.push(CheckRow {
150                qualified_name: qualified_name.clone(),
151                id,
152                sets: vec![set],
153            });
154        }
155    }
156    Ok(CheckReport { rows })
157}
158
159/// Render a report as a stable, line-oriented table.
160pub fn render_table(report: &CheckReport) -> String {
161    let mut out = String::from("name,id,sets\n");
162    for row in &report.rows {
163        out.push_str(&row.qualified_name);
164        out.push(',');
165        out.push_str(&row.id.to_string());
166        out.push(',');
167        out.push_str(&row.sets.join(";"));
168        out.push('\n');
169    }
170    out
171}
172
173fn set_label(path: &Path) -> String {
174    path.file_name()
175        .map(|name| name.to_string_lossy().into_owned())
176        .unwrap_or_else(|| path.display().to_string())
177}
178
179pub(crate) fn yaml_files(path: &Path) -> Result<Vec<PathBuf>, CheckError> {
180    if path.is_file() {
181        return Ok(vec![path.to_owned()]);
182    }
183    if !path.is_dir() {
184        return Err(CheckError::Io(format!(
185            "not a file or directory: {}",
186            path.display()
187        )));
188    }
189    let mut files = Vec::new();
190    for entry in fs::read_dir(path)
191        .map_err(|error| CheckError::Io(format!("{}: {error}", path.display())))?
192    {
193        let entry =
194            entry.map_err(|error| CheckError::Io(format!("{}: {error}", path.display())))?;
195        let file = entry.path();
196        if !file.is_file() {
197            continue;
198        }
199        let is_yaml = matches!(
200            file.extension().and_then(|ext| ext.to_str()),
201            Some("yaml" | "yml")
202        );
203        if is_yaml {
204            files.push(file);
205        }
206    }
207    files.sort();
208    Ok(files)
209}
210
211#[cfg(test)]
212mod tests {
213    use super::{CheckError, render_table, set_label};
214    use std::path::Path;
215
216    #[test]
217    fn set_label_uses_file_name() {
218        assert_eq!(set_label(Path::new("/tmp/alpha")), "alpha");
219        assert_eq!(set_label(Path::new("pose.yaml")), "pose.yaml");
220    }
221
222    #[test]
223    fn collision_error_names_both_messages() {
224        let error = CheckError::Collision {
225            set: "alpha".into(),
226            id: 7,
227            left: "left".into(),
228            right: "right".into(),
229        };
230        let text = error.to_string();
231        assert!(text.contains("left") && text.contains("right") && text.contains('7'));
232    }
233
234    #[test]
235    fn empty_table_has_header() {
236        let table = render_table(&super::CheckReport { rows: Vec::new() });
237        assert_eq!(table, "name,id,sets\n");
238    }
239}