Skip to main content

brep_ecad_core/
erc.rs

1//! Electrical rule check: what a schematic's pins say about how they may be joined,
2//! checked against the nets [`Document::netlist`] builds.
3//!
4//! A reduced form of KiCad's ERC. The pin-to-pin rules are KiCad's default pin map
5//! (`erc_settings.cpp`, the twelve electrical types), applied once per net and pair of
6//! types rather than once per pair of pins, so a net with three outputs is one finding
7//! and not three. On top of the map: a pin joined to nothing, a power input no power
8//! output or power flag drives, a no-connect pin that is joined, a no-connect marker on
9//! a joined pin, a gate (KiCad's unit) of a part split into gates with nothing joined
10//! or not placed at all, two parts with one reference, a net with two names, and a
11//! wire end that touches nothing.
12//!
13//! Every finding carries a place on the sheet to zoom to, and where one edit answers
14//! it, that edit ([`ErcFix`]).
15use crate::{Document, DocumentKind, Point, Terminal};
16use serde::{Deserialize, Serialize};
17use std::collections::{BTreeMap, BTreeSet};
18
19/// How bad a finding is, as KiCad grades them.
20#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
21pub enum ErcSeverity {
22    Error,
23    Warning,
24}
25/// What a finding is about.
26#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
27pub enum ErcKind {
28    /// A pin with no other pin on its net.
29    PinNotConnected,
30    /// Two pin types the pin map does not allow on one net.
31    PinConflict,
32    /// A power input pin on a net that no power output pin and no power flag drives.
33    PowerNotDriven,
34    /// A pin of type no_connect joined to something.
35    NoConnectJoined,
36    /// A no-connect marker on a pin that is joined after all.
37    NoConnectMarkerJoined,
38    /// Every pin of one gate of a part split into gates ([`crate::Pin::gate`],
39    /// KiCad's unit) joined to nothing.
40    UnitUnused,
41    /// A gate of a part whose gates are placed apart that has no placement:
42    /// KiCad's "missing unit". Its pins are on no sheet, so no other rule reads them.
43    UnitMissing,
44    /// Two components with one reference.
45    DuplicateReference,
46    /// Two net names on one net.
47    ConflictingLabels,
48    /// A wire end that touches no pin, wire, junction or label.
49    DanglingWire,
50}
51impl ErcKind {
52    /// The kind's name as `ecad_state` and the scripts read it.
53    pub fn key(self) -> &'static str {
54        match self {
55            Self::PinNotConnected => "pin_not_connected",
56            Self::PinConflict => "pin_conflict",
57            Self::PowerNotDriven => "power_not_driven",
58            Self::NoConnectJoined => "no_connect_joined",
59            Self::NoConnectMarkerJoined => "no_connect_marker_joined",
60            Self::UnitUnused => "unit_unused",
61            Self::UnitMissing => "unit_missing",
62            Self::DuplicateReference => "duplicate_reference",
63            Self::ConflictingLabels => "conflicting_labels",
64            Self::DanglingWire => "dangling_wire",
65        }
66    }
67}
68/// The one edit that answers a finding.
69#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
70pub enum ErcFix {
71    /// Mark these pins as meant to be left open.
72    MarkNoConnect(Vec<Terminal>),
73    /// Take the no-connect marker off this pin.
74    RemoveNoConnect(Terminal),
75    /// Put a power flag on this pin: the net is driven from off the sheet.
76    AddPowerFlag(Terminal),
77}
78impl ErcFix {
79    /// The button's words.
80    pub fn label(&self) -> &'static str {
81        match self {
82            Self::MarkNoConnect(pins) if pins.len() > 1 => "Mark its pins no-connect",
83            Self::MarkNoConnect(_) => "Mark no-connect",
84            Self::RemoveNoConnect(_) => "Remove the no-connect",
85            Self::AddPowerFlag(_) => "Add a power flag",
86        }
87    }
88}
89#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
90pub struct ErcFinding {
91    pub severity: ErcSeverity,
92    pub kind: ErcKind,
93    pub message: String,
94    /// Where on the sheet, in micrometres: the pin's tip, the component's origin or
95    /// the wire's end.
96    pub at: Point,
97    /// The pins it names, `U1.3`.
98    pub pins: Vec<String>,
99    pub fix: Option<ErcFix>,
100}
101
102/// KiCad's twelve electrical pin types, in its pin map's order.
103const TYPES: [&str; 12] = [
104    "input",
105    "output",
106    "bidirectional",
107    "tri_state",
108    "passive",
109    "free",
110    "unspecified",
111    "power_in",
112    "power_out",
113    "open_collector",
114    "open_emitter",
115    "no_connect",
116];
117const NO_CONNECT: usize = 11;
118/// A pin's electrical type as an index into [`TYPES`]. A type this build does not
119/// know reads as unspecified, as KiCad reads one.
120fn type_index(electrical_type: &str) -> usize {
121    TYPES
122        .iter()
123        .position(|t| *t == electrical_type)
124        .unwrap_or(6)
125}
126/// KiCad's default pin map: 0 allowed, 1 warning, 2 error. Symmetric.
127#[rustfmt::skip]
128const PIN_MAP: [[u8; 12]; 12] = [
129    //          In Out Bi  3S Pas NIC UnS PwI PwO OC  OE  NC
130    /* In  */ [ 0,  0,  0,  0,  0,  0,  1,  0,  0,  0,  0,  2],
131    /* Out */ [ 0,  2,  0,  1,  0,  0,  1,  0,  2,  2,  2,  2],
132    /* Bi  */ [ 0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  2],
133    /* 3S  */ [ 0,  1,  0,  0,  0,  0,  1,  1,  2,  1,  1,  2],
134    /* Pas */ [ 0,  0,  0,  0,  0,  0,  1,  0,  0,  0,  0,  2],
135    /* NIC */ [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  2],
136    /* UnS */ [ 1,  1,  1,  1,  1,  0,  1,  1,  1,  1,  1,  2],
137    /* PwI */ [ 0,  0,  0,  1,  0,  0,  1,  0,  0,  0,  0,  2],
138    /* PwO */ [ 0,  2,  1,  2,  0,  0,  1,  0,  2,  2,  2,  2],
139    /* OC  */ [ 0,  2,  0,  1,  0,  0,  1,  0,  2,  0,  0,  2],
140    /* OE  */ [ 0,  2,  1,  1,  0,  0,  1,  0,  2,  0,  0,  2],
141    /* NC  */ [ 2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2],
142];
143/// Words for a type in a message: `power_in` reads "power input".
144fn type_words(index: usize) -> &'static str {
145    [
146        "input",
147        "output",
148        "bidirectional",
149        "tri-state",
150        "passive",
151        "not internally connected",
152        "unspecified",
153        "power input",
154        "power output",
155        "open collector",
156        "open emitter",
157        "no-connect",
158    ][index]
159}
160
161impl Document {
162    /// Run the electrical rule check. Errors first, then warnings, each in sheet
163    /// order. A wiring diagram has no nets and so no findings.
164    pub fn erc(&self) -> Vec<ErcFinding> {
165        if self.kind == DocumentKind::Wiring {
166            return vec![];
167        }
168        let netlist = self.netlist();
169        let mut out = vec![];
170        let tip = |component, pin: &str| {
171            self.terminal_position(&Terminal {
172                component,
173                pin: pin.into(),
174            })
175            .unwrap_or_default()
176        };
177        let marked = |set: &[Terminal], component, pin: &str| {
178            set.iter().any(|t| t.component == component && t.pin == pin)
179        };
180        // A pin of a gate that is not placed is on no sheet: KiCad checks it only
181        // as a missing unit, below, and neither may this.
182        let unplaced = |component: crate::Uuid, number: &str| {
183            self.components.iter().find(|c| c.id == component).is_some_and(|c| {
184                c.symbol
185                    .pins
186                    .iter()
187                    .find(|p| p.number == number)
188                    .is_some_and(|p| gate_missing(c, p.gate))
189            })
190        };
191        // Pins whose net has no other pin, per component and gate, to fold a gate
192        // with nothing joined into one finding.
193        let mut open: BTreeMap<(crate::Uuid, u32), Vec<String>> = BTreeMap::new();
194        for net in &netlist.nets {
195            let placed = crate::Net {
196                pins: net
197                    .pins
198                    .iter()
199                    .filter(|p| !unplaced(p.component_id, &p.number))
200                    .cloned()
201                    .collect(),
202                ..net.clone()
203            };
204            let net = &placed;
205            let name = |p: &crate::NetPin| format!("{}.{}", p.reference, p.number);
206            if net.labels.len() > 1 {
207                let at = net.points[0];
208                out.push(ErcFinding {
209                    severity: ErcSeverity::Warning,
210                    kind: ErcKind::ConflictingLabels,
211                    message: format!(
212                        "One net has two names: {}",
213                        net.labels.iter().cloned().collect::<Vec<_>>().join(" and ")
214                    ),
215                    at,
216                    pins: net.pins.iter().map(name).collect(),
217                    fix: None,
218                });
219            }
220            // Joined: another pin, a wire, or a label on the net.
221            let joined = net.pins.len() > 1 || net.points.len() > 1 || !net.labels.is_empty();
222            for p in &net.pins {
223                let kind = type_index(&p.electrical_type);
224                let terminal = Terminal {
225                    component: p.component_id,
226                    pin: p.number.clone(),
227                };
228                if kind == NO_CONNECT {
229                    if joined {
230                        out.push(ErcFinding {
231                            severity: ErcSeverity::Error,
232                            kind: ErcKind::NoConnectJoined,
233                            message: format!("{} is a no-connect pin, but it is joined to {}", name(p), net.name),
234                            at: tip(p.component_id, &p.number),
235                            pins: vec![name(p)],
236                            fix: None,
237                        });
238                    }
239                    continue;
240                }
241                let is_marked = marked(&self.no_connects, p.component_id, &p.number);
242                if is_marked {
243                    if net.pins.len() > 1 {
244                        out.push(ErcFinding {
245                            severity: ErcSeverity::Warning,
246                            kind: ErcKind::NoConnectMarkerJoined,
247                            message: format!(
248                                "{} is marked no-connect, but it is joined to {}",
249                                name(p),
250                                net.name
251                            ),
252                            at: tip(p.component_id, &p.number),
253                            pins: vec![name(p)],
254                            fix: Some(ErcFix::RemoveNoConnect(terminal)),
255                        });
256                    }
257                    continue;
258                }
259                if net.pins.len() == 1 {
260                    let gate = self
261                        .components
262                        .iter()
263                        .find(|c| c.id == p.component_id)
264                        .filter(|c| !c.gates.is_empty())
265                        .and_then(|c| c.symbol.pins.iter().find(|q| q.number == p.number))
266                        .map_or(0, |q| q.gate);
267                    open.entry((p.component_id, gate))
268                        .or_default()
269                        .push(p.number.clone());
270                }
271            }
272            if net.pins.len() < 2 {
273                continue;
274            }
275            // The pin map, once per pair of types present on the net.
276            let mut by_type: BTreeMap<usize, Vec<String>> = BTreeMap::new();
277            for p in &net.pins {
278                let kind = type_index(&p.electrical_type);
279                if kind != NO_CONNECT && !marked(&self.no_connects, p.component_id, &p.number) {
280                    by_type.entry(kind).or_default().push(name(p));
281                }
282            }
283            let kinds: Vec<usize> = by_type.keys().copied().collect();
284            for (i, &a) in kinds.iter().enumerate() {
285                for &b in &kinds[i..] {
286                    let level = PIN_MAP[a][b];
287                    if level == 0 || (a == b && by_type[&a].len() < 2) {
288                        continue;
289                    }
290                    let mut pins = by_type[&a].clone();
291                    if a != b {
292                        pins.extend(by_type[&b].iter().cloned());
293                    }
294                    let message = if a == b {
295                        format!("{}: {} {} pins joined ({})", net.name, pins.len(), type_words(a), pins.join(", "))
296                    } else {
297                        format!(
298                            "{}: {} pin {} joined to {} pin {}",
299                            net.name,
300                            type_words(a),
301                            by_type[&a].join(", "),
302                            type_words(b),
303                            by_type[&b].join(", ")
304                        )
305                    };
306                    let first = net
307                        .pins
308                        .iter()
309                        .find(|p| name(p) == pins[0])
310                        .unwrap();
311                    out.push(ErcFinding {
312                        severity: if level == 2 {
313                            ErcSeverity::Error
314                        } else {
315                            ErcSeverity::Warning
316                        },
317                        kind: ErcKind::PinConflict,
318                        message,
319                        at: tip(first.component_id, &first.number),
320                        pins,
321                        fix: None,
322                    });
323                }
324            }
325            // A power input needs a power output or a power flag on its net.
326            let power_in: Vec<&crate::NetPin> = net
327                .pins
328                .iter()
329                .filter(|p| p.electrical_type == "power_in")
330                .collect();
331            let driven = net.pins.iter().any(|p| {
332                p.electrical_type == "power_out" || marked(&self.power_flags, p.component_id, &p.number)
333            });
334            if let Some(first) = power_in.first()
335                && !driven
336            {
337                out.push(ErcFinding {
338                    severity: ErcSeverity::Error,
339                    kind: ErcKind::PowerNotDriven,
340                    message: format!(
341                        "{}: power input {} is not driven: no power output is on the net",
342                        net.name,
343                        power_in.iter().map(|p| name(p)).collect::<Vec<_>>().join(", ")
344                    ),
345                    at: tip(first.component_id, &first.number),
346                    pins: power_in.iter().map(|p| name(p)).collect(),
347                    fix: Some(ErcFix::AddPowerFlag(Terminal {
348                        component: first.component_id,
349                        pin: first.number.clone(),
350                    })),
351                });
352            }
353        }
354        // Pins joined to nothing: a whole unused gate of a part placed as gates is
355        // one warning, every other pin its own error. Keyed on the GATE, not on
356        // `Pin::unit`, which says which port group a pin is on.
357        for ((component, gate), pins) in open {
358            let Some(c) = self.components.iter().find(|c| c.id == component) else {
359                continue;
360            };
361            let gate_pins: Vec<_> = c
362                .symbol
363                .pins
364                .iter()
365                .filter(|p| p.gate == gate && type_index(&p.electrical_type) != NO_CONNECT)
366                .filter(|p| !marked(&self.no_connects, component, &p.number))
367                .collect();
368            let whole_gate = gate > 0
369                && gate_pins.len() == pins.len()
370                && !gate_pins.iter().any(|p| p.electrical_type == "power_in");
371            if whole_gate {
372                out.push(ErcFinding {
373                    severity: ErcSeverity::Warning,
374                    kind: ErcKind::UnitUnused,
375                    message: format!(
376                        "{} is unused: none of its pins {} is joined",
377                        c.gate_reference(gate),
378                        pins.join(", ")
379                    ),
380                    at: tip(component, &pins[0]),
381                    pins: pins.iter().map(|n| format!("{}.{n}", c.reference)).collect(),
382                    fix: Some(ErcFix::MarkNoConnect(
383                        pins.iter()
384                            .map(|pin| Terminal {
385                                component,
386                                pin: pin.clone(),
387                            })
388                            .collect(),
389                    )),
390                });
391                continue;
392            }
393            for number in pins {
394                let pin = c.symbol.pins.iter().find(|p| p.number == number);
395                let words = pin.map_or("unspecified", |p| type_words(type_index(&p.electrical_type)));
396                let pin_name = pin
397                    .map(|p| p.name.as_str())
398                    .filter(|n| !n.is_empty() && *n != "~" && **n != number)
399                    .map(|n| format!(" ({n})"))
400                    .unwrap_or_default();
401                out.push(ErcFinding {
402                    severity: ErcSeverity::Error,
403                    kind: ErcKind::PinNotConnected,
404                    message: format!("{}.{number}{pin_name}, {words}, is not connected", c.reference),
405                    at: tip(component, &number),
406                    pins: vec![format!("{}.{number}", c.reference)],
407                    fix: Some(ErcFix::MarkNoConnect(vec![Terminal {
408                        component,
409                        pin: number.clone(),
410                    }])),
411                });
412            }
413        }
414        // A gate of a part placed as gates that has no placement.
415        for c in &self.components {
416            if c.gates.is_empty() {
417                continue;
418            }
419            for gate in (1..=c.symbol.gate_count()).filter(|&g| gate_missing(c, g)) {
420                let pins: Vec<_> = c.symbol.pins.iter().filter(|p| p.gate == gate).collect();
421                if pins.is_empty() {
422                    continue;
423                }
424                let power = pins.iter().any(|p| p.electrical_type == "power_in");
425                out.push(ErcFinding {
426                    severity: if power { ErcSeverity::Error } else { ErcSeverity::Warning },
427                    kind: ErcKind::UnitMissing,
428                    message: format!(
429                        "{} is not placed{}: its pins {} are on no sheet",
430                        c.gate_reference(gate),
431                        if power { ", so the part has no power" } else { "" },
432                        pins.iter().map(|p| p.number.as_str()).collect::<Vec<_>>().join(", ")
433                    ),
434                    at: c.at,
435                    pins: pins.iter().map(|p| format!("{}.{}", c.reference, p.number)).collect(),
436                    fix: None,
437                });
438            }
439        }
440        let mut seen: BTreeMap<&str, Vec<&crate::Component>> = BTreeMap::new();
441        for c in &self.components {
442            seen.entry(c.reference.as_str()).or_default().push(c);
443        }
444        for (reference, parts) in seen {
445            if parts.len() > 1 {
446                out.push(ErcFinding {
447                    severity: ErcSeverity::Error,
448                    kind: ErcKind::DuplicateReference,
449                    message: format!("{} parts are called {reference}", parts.len()),
450                    at: parts[1].at,
451                    pins: vec![],
452                    fix: None,
453                });
454            }
455        }
456        out.extend(self.dangling_wire_ends());
457        out.sort_by(|a, b| (a.severity, a.at.y, a.at.x).cmp(&(b.severity, b.at.y, b.at.x)));
458        out
459    }
460    /// A wire end that touches no pin, no other wire, no junction and no label.
461    fn dangling_wire_ends(&self) -> Vec<ErcFinding> {
462        let mut anchors: BTreeSet<Point> = self.junctions.iter().copied().collect();
463        anchors.extend(self.labels.iter().map(|l| l.at));
464        for c in &self.components {
465            anchors.extend(c.symbol.pins.iter().map(|p| c.pin_at(p)));
466        }
467        let mut out = vec![];
468        for (i, w) in self.wires.iter().enumerate() {
469            for end in [w.a, w.b] {
470                let touches = anchors.contains(&end)
471                    || self.wires.iter().enumerate().any(|(j, other)| {
472                        j != i
473                            && other
474                                .points()
475                                .windows(2)
476                                .any(|s| crate::on_segment(end, s[0], s[1]))
477                    });
478                if !touches {
479                    out.push(ErcFinding {
480                        severity: ErcSeverity::Warning,
481                        kind: ErcKind::DanglingWire,
482                        message: format!(
483                            "A wire ends at ({:.2}, {:.2}) mm on nothing",
484                            end.x as f64 / 1000.,
485                            end.y as f64 / 1000.
486                        ),
487                        at: end,
488                        pins: vec![],
489                        fix: None,
490                    });
491                }
492            }
493        }
494        out
495    }
496    /// Make the edit a finding offers.
497    pub fn apply_erc_fix(&mut self, fix: &ErcFix) {
498        match fix {
499            ErcFix::MarkNoConnect(pins) => {
500                for t in pins {
501                    if !self.no_connects.contains(t) {
502                        self.no_connects.push(t.clone());
503                    }
504                }
505            }
506            ErcFix::RemoveNoConnect(t) => self.no_connects.retain(|n| n != t),
507            ErcFix::AddPowerFlag(t) => {
508                if !self.power_flags.contains(t) {
509                    self.power_flags.push(t.clone());
510                }
511            }
512        }
513    }
514}
515/// Whether gate `gate` of `c` has no placement although `c` places its gates apart.
516/// A component drawn whole (no gate placements) misses none.
517fn gate_missing(c: &crate::Component, gate: u32) -> bool {
518    gate > 0 && !c.gates.is_empty() && c.symbol.gate_count() > 1 && c.gate(gate).is_none()
519}