1use std::fmt;
10
11#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
13pub enum KiCadDiagnosticSeverity {
14 Error,
16 Warning,
18 Info,
20}
21
22impl KiCadDiagnosticSeverity {
23 pub const fn as_str(self) -> &'static str {
24 match self {
25 Self::Error => "error",
26 Self::Warning => "warning",
27 Self::Info => "info",
28 }
29 }
30}
31
32#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
34pub enum KiCadDiagnosticCode {
35 SheetFileMissing,
39 SheetFileUnreadable,
44 SheetRecursion,
49 UuidRepeated,
53 ObjectNotDrawn,
56 ComponentUnitRepeated,
60 ComponentUnitDefinitionsDiffer,
65 ProjectUnreadable,
68 ConnectivityNotCompiled,
71 PinContactEvidenceDiffers,
77 PinIdentityRepeated,
83 BusAliasCycle,
90}
91
92impl KiCadDiagnosticCode {
93 pub const fn as_str(self) -> &'static str {
94 match self {
95 Self::SheetFileMissing => "sheet_file_missing",
96 Self::SheetFileUnreadable => "sheet_file_unreadable",
97 Self::SheetRecursion => "sheet_recursion",
98 Self::UuidRepeated => "uuid_repeated",
99 Self::ObjectNotDrawn => "object_not_drawn",
100 Self::ComponentUnitRepeated => "component_unit_repeated",
101 Self::ComponentUnitDefinitionsDiffer => "component_unit_definitions_differ",
102 Self::ProjectUnreadable => "project_unreadable",
103 Self::ConnectivityNotCompiled => "connectivity_not_compiled",
104 Self::PinContactEvidenceDiffers => "pin_contact_evidence_differs",
105 Self::PinIdentityRepeated => "pin_identity_repeated",
106 Self::BusAliasCycle => "bus_alias_cycle",
107 }
108 }
109
110 pub const fn severity(self) -> KiCadDiagnosticSeverity {
111 match self {
112 Self::SheetFileMissing
113 | Self::SheetFileUnreadable
114 | Self::ObjectNotDrawn
115 | Self::ProjectUnreadable
116 | Self::ConnectivityNotCompiled => KiCadDiagnosticSeverity::Error,
117 Self::PinContactEvidenceDiffers | Self::PinIdentityRepeated | Self::BusAliasCycle => {
118 KiCadDiagnosticSeverity::Warning
119 }
120 Self::SheetRecursion
121 | Self::UuidRepeated
122 | Self::ComponentUnitRepeated
123 | Self::ComponentUnitDefinitionsDiffer => KiCadDiagnosticSeverity::Info,
124 }
125 }
126}
127
128impl KiCadDiagnosticCode {
129 pub const fn concerns_drawing(self) -> bool {
132 !matches!(
133 self,
134 Self::ComponentUnitRepeated
135 | Self::ComponentUnitDefinitionsDiffer
136 | Self::ConnectivityNotCompiled
137 | Self::PinContactEvidenceDiffers
138 | Self::PinIdentityRepeated
139 | Self::BusAliasCycle
140 )
141 }
142}
143
144impl fmt::Display for KiCadDiagnosticCode {
145 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
146 formatter.write_str(self.as_str())
147 }
148}
149
150#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
152pub struct KiCadDiagnostic {
153 pub occurrence: Option<String>,
155 pub source_path: String,
157 pub code: KiCadDiagnosticCode,
158 pub object_kind: String,
160 pub object_uuid: Option<String>,
161 pub message: String,
162}
163
164impl KiCadDiagnostic {
165 pub fn new(
166 code: KiCadDiagnosticCode,
167 source_path: impl Into<String>,
168 object_kind: impl Into<String>,
169 object_uuid: Option<String>,
170 message: impl Into<String>,
171 ) -> Self {
172 Self {
173 occurrence: None,
174 source_path: source_path.into(),
175 code,
176 object_kind: object_kind.into(),
177 object_uuid: object_uuid.filter(|value| !value.is_empty()),
178 message: message.into(),
179 }
180 }
181
182 #[must_use]
183 pub fn on_occurrence(mut self, occurrence: impl Into<String>) -> Self {
184 self.occurrence = Some(occurrence.into());
185 self
186 }
187
188 pub const fn severity(&self) -> KiCadDiagnosticSeverity {
189 self.code.severity()
190 }
191}
192
193pub fn sorted_diagnostics(
196 diagnostics: impl IntoIterator<Item = KiCadDiagnostic>,
197) -> Vec<KiCadDiagnostic> {
198 let mut rows = diagnostics.into_iter().collect::<Vec<_>>();
199 rows.sort_by(|left, right| sort_key(left).cmp(&sort_key(right)));
200 rows.dedup();
201 rows
202}
203
204fn sort_key(diagnostic: &KiCadDiagnostic) -> (&str, &str, &str, &str, &str, &str) {
205 (
206 diagnostic.occurrence.as_deref().unwrap_or(""),
207 &diagnostic.source_path,
208 diagnostic.code.as_str(),
209 &diagnostic.object_kind,
210 diagnostic.object_uuid.as_deref().unwrap_or(""),
211 &diagnostic.message,
212 )
213}
214
215pub const PIN_UUID_MIN_VERSION: i64 = 20_210_126;
218
219#[derive(Clone, Debug, Eq, PartialEq)]
221pub struct RepeatedUuid {
222 pub offset: usize,
223 pub original: String,
224 pub replacement: String,
225 pub owner: String,
227}
228
229pub fn effective_uuid_text(text: &str) -> Option<(String, Vec<RepeatedUuid>)> {
239 let mut scanner = UuidScanner::default();
240 let mut repeats = Vec::new();
241 for token in tokens(text) {
242 if let Some(repeat) = scanner.feed(token) {
243 repeats.push(repeat);
244 }
245 }
246 if repeats.is_empty() {
247 return None;
248 }
249 let mut output = String::with_capacity(text.len());
250 let mut cursor = 0;
251 for repeat in &repeats {
252 output.push_str(&text[cursor..repeat.offset]);
253 output.push_str(&repeat.replacement);
254 cursor = repeat.offset + repeat.original.len();
255 }
256 output.push_str(&text[cursor..]);
257 Some((output, repeats))
258}
259
260#[derive(Clone, Copy)]
261struct Token<'a> {
262 text: &'a str,
263 offset: usize,
264}
265
266fn tokens(text: &str) -> impl Iterator<Item = Token<'_>> {
267 let bytes = text.as_bytes();
268 let mut index = 0;
269 std::iter::from_fn(move || {
270 while index < bytes.len() && bytes[index].is_ascii_whitespace() {
271 index += 1;
272 }
273 if index >= bytes.len() {
274 return None;
275 }
276 let start = index;
277 index = match bytes[index] {
278 b'(' | b')' => index + 1,
279 b'"' => quoted_end(bytes, index),
280 _ => atom_end(bytes, index),
281 };
282 Some(Token {
283 text: text.get(start..index).unwrap_or(""),
284 offset: start,
285 })
286 })
287}
288
289fn quoted_end(bytes: &[u8], start: usize) -> usize {
291 let mut index = start + 1;
292 while index < bytes.len() && bytes[index] != b'"' {
293 index += if bytes[index] == b'\\' { 2 } else { 1 };
294 }
295 (index + 1).min(bytes.len())
296}
297
298fn atom_end(bytes: &[u8], start: usize) -> usize {
300 let mut index = start;
301 while index < bytes.len()
302 && !bytes[index].is_ascii_whitespace()
303 && !matches!(bytes[index], b'(' | b')' | b'"')
304 {
305 index += 1;
306 }
307 index
308}
309
310#[derive(Default)]
311struct UuidScanner {
312 heads: Vec<String>,
313 expect_head: bool,
314 version: Option<i64>,
315 pending_version: bool,
316 pending_uuid: Option<String>,
317 used: std::collections::HashSet<String>,
318}
319
320impl UuidScanner {
321 fn feed(&mut self, token: Token<'_>) -> Option<RepeatedUuid> {
322 match token.text {
323 "(" => {
324 self.expect_head = true;
325 return None;
326 }
327 ")" => {
328 self.heads.pop();
329 self.expect_head = false;
330 self.pending_version = false;
331 self.pending_uuid = None;
332 return None;
333 }
334 _ => {}
335 }
336 if self.expect_head {
337 self.expect_head = false;
338 self.heads.push(token.text.to_owned());
339 self.pending_version = token.text == "version" && self.heads.len() == 2;
340 self.pending_uuid = (token.text == "uuid").then(|| self.uuid_owner());
341 return None;
342 }
343 if self.pending_version {
344 self.pending_version = false;
345 self.version = token.text.parse().ok();
346 return None;
347 }
348 let owner = self.pending_uuid.take()?;
349 if owner.is_empty() {
350 return None;
351 }
352 let quoted = token.text.starts_with('"');
353 let value = if quoted {
354 token.text.get(1..token.text.len().saturating_sub(1))?
355 } else {
356 token.text
357 };
358 let offset = token.offset + usize::from(quoted);
359 let mut replacement = value.to_owned();
360 let mut key = uuid_key(&replacement);
361 while self.used.contains(&key) {
362 let next = increment_uuid_text(&replacement);
363 if next == replacement {
364 break;
365 }
366 replacement = next;
367 key = uuid_key(&replacement);
368 }
369 self.used.insert(key);
370 (replacement != value).then(|| RepeatedUuid {
371 offset,
372 original: value.to_owned(),
373 replacement,
374 owner,
375 })
376 }
377
378 fn uuid_owner(&self) -> String {
381 let depth = self.heads.len();
382 let parent = depth
383 .checked_sub(2)
384 .map_or("", |index| self.heads[index].as_str());
385 let grandparent = depth
386 .checked_sub(3)
387 .map_or("", |index| self.heads[index].as_str());
388 let old_pin = parent == "pin"
389 && grandparent == "symbol"
390 && depth == 4
391 && self.version.unwrap_or(0) < PIN_UUID_MIN_VERSION;
392 if old_pin || parent == "ellipse" {
393 String::new()
394 } else {
395 parent.to_owned()
396 }
397 }
398}
399
400fn uuid_key(value: &str) -> String {
401 let text = value.to_ascii_lowercase();
402 if text.len() == 8 && text.bytes().all(|byte| byte.is_ascii_hexdigit()) {
403 format!("00000000-0000-0000-0000-0000{text}")
404 } else {
405 text
406 }
407}
408
409pub(crate) fn direct_uuid(form: &str) -> Option<String> {
411 let mut depth = 0_usize;
412 let mut expect_head = false;
413 let mut in_uuid = false;
414 for token in tokens(form) {
415 match token.text {
416 "(" => {
417 depth += 1;
418 expect_head = true;
419 }
420 ")" => {
421 depth = depth.saturating_sub(1);
422 in_uuid = false;
423 }
424 text if expect_head => {
425 expect_head = false;
426 in_uuid = depth == 2 && text == "uuid";
427 }
428 text if in_uuid => {
429 return Some(text.trim_matches('"').to_owned());
430 }
431 _ => {}
432 }
433 }
434 None
435}
436
437pub fn increment_uuid_text(value: &str) -> String {
442 let digits = value
443 .bytes()
444 .filter(|byte| *byte != b'-')
445 .collect::<Vec<_>>();
446 if digits.is_empty() || !digits.iter().all(u8::is_ascii_hexdigit) {
447 return value.to_owned();
448 }
449 let mut nibbles = digits
450 .iter()
451 .map(|byte| char::from(*byte).to_digit(16).unwrap_or(0))
452 .collect::<Vec<_>>();
453 for nibble in nibbles.iter_mut().rev() {
454 *nibble = (*nibble + 1) % 16;
455 if *nibble != 0 {
456 break;
457 }
458 }
459 let mut next = nibbles.into_iter();
460 value
461 .chars()
462 .map(|character| {
463 if character == '-' {
464 '-'
465 } else {
466 next.next()
467 .and_then(|nibble| char::from_digit(nibble, 16))
468 .unwrap_or('0')
469 }
470 })
471 .collect()
472}
473
474#[cfg(test)]
475mod tests {
476 use super::*;
477
478 #[test]
479 fn increments_with_carry_like_kiid() {
480 assert_eq!(
481 increment_uuid_text("7cd130fb-b637-4ed5-853c-146668691e1f"),
482 "7cd130fb-b637-4ed5-853c-146668691e20"
483 );
484 assert_eq!(
485 increment_uuid_text("ffffffff-ffff-ffff-ffff-ffffffffffff"),
486 "00000000-0000-0000-0000-000000000000"
487 );
488 }
489
490 #[test]
491 fn repeats_follow_file_order_and_skip_old_pins_and_ellipses() {
492 let text = "(kicad_sch (version 20200512) (uuid \"a\")\n\
493 (wire (uuid 7cd130fb-b637-4ed5-853c-146668691e13))\n\
494 (wire (uuid 7cd130fb-b637-4ed5-853c-146668691e13))\n\
495 (symbol (uuid 7cd130fb-b637-4ed5-853c-146668691e14) (pin \"1\" (uuid 7cd130fb-b637-4ed5-853c-146668691e14)))\n\
496 (ellipse (uuid 7cd130fb-b637-4ed5-853c-146668691e13)))";
497 let (output, repeats) = effective_uuid_text(text).unwrap();
498 assert_eq!(repeats.len(), 2);
499 assert_eq!(
500 repeats[0].replacement,
501 "7cd130fb-b637-4ed5-853c-146668691e14"
502 );
503 assert_eq!(repeats[1].original, "7cd130fb-b637-4ed5-853c-146668691e14");
504 assert_eq!(
505 repeats[1].replacement,
506 "7cd130fb-b637-4ed5-853c-146668691e15"
507 );
508 assert_eq!(output.len(), text.len());
509 assert!(effective_uuid_text("(kicad_sch (uuid a) (wire (uuid b)))").is_none());
510 }
511}