Skip to main content
← Back to kicad-monkey Rust Docs kicad-monkey Rust Crate API Reference

kicad_monkey_core/
schematic_diagnostics.rs

1//! Schematic diagnostics that travel beside the Plotter IR, never inside it.
2//!
3//! KiCad Monkey does not stop a page or a project for something it does not
4//! fully handle. It draws by KiCad's rule, or by its best rule, and reports a
5//! diagnostic here, so the Plotter IR stays comparable with KiCad's own plot.
6//! The codes are shared with Python's `kicad_monkey.kicad_diagnostics`.
7//! Citations are paths in the KiCad source tree.
8
9use std::fmt;
10
11/// How a diagnostic relates to what was drawn.
12#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
13pub enum KiCadDiagnosticSeverity {
14    /// The object was left out.
15    Error,
16    /// The object was drawn by a rule not yet checked against KiCad.
17    Warning,
18    /// The object was skipped the way KiCad skips it.
19    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/// Stable diagnostic codes. Each one names the KiCad behaviour it follows.
33#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
34pub enum KiCadDiagnosticCode {
35    /// A sheet whose file is missing keeps its sheet symbol and gets an empty
36    /// page; loading continues
37    /// (eeschema/sch_io/kicad_sexpr/sch_io_kicad_sexpr.cpp:264-296).
38    SheetFileMissing,
39    /// A sheet whose file cannot be read or parsed gets an empty page and the
40    /// rest of the hierarchy loads; only the root sheet stops KiCad
41    /// (eeschema/sch_io/kicad_sexpr/sch_io_kicad_sexpr.cpp:269-283). KiCad
42    /// Monkey also draws an empty root page instead of stopping.
43    SheetFileUnreadable,
44    /// A sheet that repeats one of its direct ancestors is not loaded, gets no
45    /// page, and its sheet symbol is removed from the parent page
46    /// (eeschema/sch_io/kicad_sexpr/sch_io_kicad_sexpr.cpp:217-237;
47    /// eeschema/sch_sheet_path.cpp:1116-1144).
48    SheetRecursion,
49    /// A UUID repeated within one file is made unique while loading, by
50    /// incrementing it until it is unused
51    /// (eeschema/sch_io/kicad_sexpr/sch_io_kicad_sexpr_parser.cpp:118-128).
52    UuidRepeated,
53    /// KiCad Monkey could not draw this object; it is left out and the rest of
54    /// the page is drawn.
55    ObjectNotDrawn,
56    /// Several symbols claim the same unit of one reference. KiCad's netlist
57    /// takes a multi-unit reference once and keeps one pin per pin number
58    /// (eeschema/netlist_exporters/netlist_exporter_base.cpp:231-270,457).
59    ComponentUnitRepeated,
60    /// Units of one reference use different cached library symbols. Each unit
61    /// draws its own; the netlist takes the component's library facts from
62    /// its first unit
63    /// (eeschema/netlist_exporters/netlist_exporter_base.cpp:254-303).
64    ComponentUnitDefinitionsDiffer,
65    /// The project file could not be read; its settings are left out and
66    /// KiCad's defaults are used.
67    ProjectUnreadable,
68    /// KiCad Monkey could not compile the design's connectivity. Every page
69    /// is still drawn; nets, terminals and their bindings are left out.
70    ConnectivityNotCompiled,
71    /// Drawn pins of one symbol that share a number reach one contact with
72    /// different source or no-connect evidence. KiCad's netlist keeps one pin
73    /// per number (eeschema/netlist_exporters/netlist_exporter_base.cpp:
74    /// 402-447); the contact keeps the first pin's evidence. Not yet checked
75    /// against KiCad for the no-connect marker.
76    PinContactEvidenceDiffers,
77    /// Drawn pins of one symbol that share a number have no saved pin UUID to
78    /// tell them apart and reach different nets. KiCad gives each a new UUID
79    /// on load and keeps them apart (eeschema/sch_symbol.cpp:1288-1311); the
80    /// compiled graph has no stable identity for the later pin, so its
81    /// terminal keeps the first pin's net. The netlist lists every net.
82    PinIdentityRepeated,
83    /// A bus label's expansion met an alias again inside its own expansion;
84    /// the repeated alias is one scalar bus member. KiCad looks a name up as
85    /// an alias only where it is a bus group member and configures each alias
86    /// member as a label, so a bare member name is a plain net and aliases
87    /// cannot loop (eeschema/sch_connection.cpp:184-205). KiCad Monkey also
88    /// expands bare alias members, so its members can differ from KiCad's.
89    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    /// Whether the diagnostic is about what a page draws. Connectivity and
130    /// component facts stay on the compilation and are not page diagnostics.
131    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/// One diagnostic about one source object.
151#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
152pub struct KiCadDiagnostic {
153    /// Hierarchy occurrence address of the page it belongs to, when known.
154    pub occurrence: Option<String>,
155    /// Bundle path of the source file that holds the object.
156    pub source_path: String,
157    pub code: KiCadDiagnosticCode,
158    /// Source form head, for example `sheet`, `symbol` or `wire`.
159    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
193/// Stable order shared with Python: occurrence, source path, code, object
194/// kind, object UUID, message. Repeats are removed.
195pub 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
215/// Placed-symbol pin UUIDs written before this version are ignored by KiCad
216/// (eeschema/sch_io/kicad_sexpr/sch_io_kicad_sexpr_parser.cpp:4124-4134).
217pub const PIN_UUID_MIN_VERSION: i64 = 20_210_126;
218
219/// One `(uuid ...)` value KiCad would make unique while loading.
220#[derive(Clone, Debug, Eq, PartialEq)]
221pub struct RepeatedUuid {
222    pub offset: usize,
223    pub original: String,
224    pub replacement: String,
225    /// Head of the form that owns the UUID.
226    pub owner: String,
227}
228
229/// Apply KiCad's load rule for repeated UUIDs to one schematic file.
230///
231/// KiCad's parser keeps a set of the UUIDs it has read from the file and
232/// increments a repeat until it is unused
233/// (eeschema/sch_io/kicad_sexpr/sch_io_kicad_sexpr_parser.cpp:118-128;
234/// common/kiid.cpp:299-311). Ellipse bodies keep their raw value (:5422), and
235/// placed-symbol pin UUIDs in files older than 20210126 are ignored
236/// (:4124-4134). Replacements keep the textual width, so byte offsets into the
237/// text stay valid. Returns `None` when nothing repeats.
238pub 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
289/// Byte after the closing quote of the string starting at `start`.
290fn 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
298/// Byte after the bare atom starting at `start`.
299fn 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    /// Head of the form owning a `(uuid ...)`, or empty when KiCad does not
379    /// enter it in its set of read UUIDs.
380    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
409/// The `(uuid ...)` value directly inside one form's text, if any.
410pub(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
437/// Increment a hexadecimal UUID by one, keeping its textual width and dashes,
438/// as KiCad's `KIID::Increment` adds one to the 128-bit value
439/// (common/kiid.cpp:299-311). A value that is not hexadecimal is returned
440/// unchanged.
441pub 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}