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        // A sub-board's parts, nets and markers are checked in its own document.
169        if !self.zones.is_empty() {
170            return self.without_zones().erc();
171        }
172        let netlist = self.netlist();
173        let mut out = vec![];
174        let tip = |component, pin: &str| {
175            self.terminal_position(&Terminal {
176                component,
177                pin: pin.into(),
178            })
179            .unwrap_or_default()
180        };
181        let marked = |set: &[Terminal], component, pin: &str| {
182            set.iter().any(|t| t.component == component && t.pin == pin)
183        };
184        // A pin of a gate that is not placed is on no sheet: KiCad checks it only
185        // as a missing unit, below, and neither may this.
186        let unplaced = |component: crate::Uuid, number: &str| {
187            self.components.iter().find(|c| c.id == component).is_some_and(|c| {
188                c.symbol
189                    .pins
190                    .iter()
191                    .find(|p| p.number == number)
192                    .is_some_and(|p| gate_missing(c, p.gate))
193            })
194        };
195        // Pins whose net has no other pin, per component and gate, to fold a gate
196        // with nothing joined into one finding.
197        let mut open: BTreeMap<(crate::Uuid, u32), Vec<String>> = BTreeMap::new();
198        for net in &netlist.nets {
199            let placed = crate::Net {
200                pins: net
201                    .pins
202                    .iter()
203                    .filter(|p| !unplaced(p.component_id, &p.number))
204                    .cloned()
205                    .collect(),
206                ..net.clone()
207            };
208            let net = &placed;
209            let name = |p: &crate::NetPin| format!("{}.{}", p.reference, p.number);
210            if net.labels.len() > 1 {
211                let at = net.points[0];
212                out.push(ErcFinding {
213                    severity: ErcSeverity::Warning,
214                    kind: ErcKind::ConflictingLabels,
215                    message: format!(
216                        "One net has two names: {}",
217                        net.labels.iter().cloned().collect::<Vec<_>>().join(" and ")
218                    ),
219                    at,
220                    pins: net.pins.iter().map(name).collect(),
221                    fix: None,
222                });
223            }
224            // Joined: another pin, a wire, or a label on the net.
225            let joined = net.pins.len() > 1 || net.points.len() > 1 || !net.labels.is_empty();
226            for p in &net.pins {
227                let kind = type_index(&p.electrical_type);
228                let terminal = Terminal {
229                    component: p.component_id,
230                    pin: p.number.clone(),
231                };
232                if kind == NO_CONNECT {
233                    if joined {
234                        out.push(ErcFinding {
235                            severity: ErcSeverity::Error,
236                            kind: ErcKind::NoConnectJoined,
237                            message: format!("{} is a no-connect pin, but it is joined to {}", name(p), net.name),
238                            at: tip(p.component_id, &p.number),
239                            pins: vec![name(p)],
240                            fix: None,
241                        });
242                    }
243                    continue;
244                }
245                let is_marked = marked(&self.no_connects, p.component_id, &p.number);
246                if is_marked {
247                    if net.pins.len() > 1 {
248                        out.push(ErcFinding {
249                            severity: ErcSeverity::Warning,
250                            kind: ErcKind::NoConnectMarkerJoined,
251                            message: format!(
252                                "{} is marked no-connect, but it is joined to {}",
253                                name(p),
254                                net.name
255                            ),
256                            at: tip(p.component_id, &p.number),
257                            pins: vec![name(p)],
258                            fix: Some(ErcFix::RemoveNoConnect(terminal)),
259                        });
260                    }
261                    continue;
262                }
263                if net.pins.len() == 1 {
264                    let gate = self
265                        .components
266                        .iter()
267                        .find(|c| c.id == p.component_id)
268                        .filter(|c| !c.gates.is_empty())
269                        .and_then(|c| c.symbol.pins.iter().find(|q| q.number == p.number))
270                        .map_or(0, |q| q.gate);
271                    open.entry((p.component_id, gate))
272                        .or_default()
273                        .push(p.number.clone());
274                }
275            }
276            if net.pins.len() < 2 {
277                continue;
278            }
279            // The pin map, once per pair of types present on the net.
280            let mut by_type: BTreeMap<usize, Vec<String>> = BTreeMap::new();
281            for p in &net.pins {
282                let kind = type_index(&p.electrical_type);
283                if kind != NO_CONNECT && !marked(&self.no_connects, p.component_id, &p.number) {
284                    by_type.entry(kind).or_default().push(name(p));
285                }
286            }
287            let kinds: Vec<usize> = by_type.keys().copied().collect();
288            for (i, &a) in kinds.iter().enumerate() {
289                for &b in &kinds[i..] {
290                    let level = PIN_MAP[a][b];
291                    if level == 0 || (a == b && by_type[&a].len() < 2) {
292                        continue;
293                    }
294                    let mut pins = by_type[&a].clone();
295                    if a != b {
296                        pins.extend(by_type[&b].iter().cloned());
297                    }
298                    let message = if a == b {
299                        format!("{}: {} {} pins joined ({})", net.name, pins.len(), type_words(a), pins.join(", "))
300                    } else {
301                        format!(
302                            "{}: {} pin {} joined to {} pin {}",
303                            net.name,
304                            type_words(a),
305                            by_type[&a].join(", "),
306                            type_words(b),
307                            by_type[&b].join(", ")
308                        )
309                    };
310                    let first = net
311                        .pins
312                        .iter()
313                        .find(|p| name(p) == pins[0])
314                        .unwrap();
315                    out.push(ErcFinding {
316                        severity: if level == 2 {
317                            ErcSeverity::Error
318                        } else {
319                            ErcSeverity::Warning
320                        },
321                        kind: ErcKind::PinConflict,
322                        message,
323                        at: tip(first.component_id, &first.number),
324                        pins,
325                        fix: None,
326                    });
327                }
328            }
329            // A power input needs a power output or a power flag on its net.
330            let power_in: Vec<&crate::NetPin> = net
331                .pins
332                .iter()
333                .filter(|p| p.electrical_type == "power_in")
334                .collect();
335            let driven = net.pins.iter().any(|p| {
336                p.electrical_type == "power_out" || marked(&self.power_flags, p.component_id, &p.number)
337            });
338            if let Some(first) = power_in.first()
339                && !driven
340            {
341                out.push(ErcFinding {
342                    severity: ErcSeverity::Error,
343                    kind: ErcKind::PowerNotDriven,
344                    message: format!(
345                        "{}: power input {} is not driven: no power output is on the net",
346                        net.name,
347                        power_in.iter().map(|p| name(p)).collect::<Vec<_>>().join(", ")
348                    ),
349                    at: tip(first.component_id, &first.number),
350                    pins: power_in.iter().map(|p| name(p)).collect(),
351                    fix: Some(ErcFix::AddPowerFlag(Terminal {
352                        component: first.component_id,
353                        pin: first.number.clone(),
354                    })),
355                });
356            }
357        }
358        // Pins joined to nothing: a whole unused gate of a part placed as gates is
359        // one warning, every other pin its own error. Keyed on the GATE, not on
360        // `Pin::unit`, which says which port group a pin is on.
361        for ((component, gate), pins) in open {
362            let Some(c) = self.components.iter().find(|c| c.id == component) else {
363                continue;
364            };
365            let gate_pins: Vec<_> = c
366                .symbol
367                .pins
368                .iter()
369                .filter(|p| p.gate == gate && type_index(&p.electrical_type) != NO_CONNECT)
370                .filter(|p| !marked(&self.no_connects, component, &p.number))
371                .collect();
372            let whole_gate = gate > 0
373                && gate_pins.len() == pins.len()
374                && !gate_pins.iter().any(|p| p.electrical_type == "power_in");
375            if whole_gate {
376                out.push(ErcFinding {
377                    severity: ErcSeverity::Warning,
378                    kind: ErcKind::UnitUnused,
379                    message: format!(
380                        "{} is unused: none of its pins {} is joined",
381                        c.gate_reference(gate),
382                        pins.join(", ")
383                    ),
384                    at: tip(component, &pins[0]),
385                    pins: pins.iter().map(|n| format!("{}.{n}", c.reference)).collect(),
386                    fix: Some(ErcFix::MarkNoConnect(
387                        pins.iter()
388                            .map(|pin| Terminal {
389                                component,
390                                pin: pin.clone(),
391                            })
392                            .collect(),
393                    )),
394                });
395                continue;
396            }
397            for number in pins {
398                let pin = c.symbol.pins.iter().find(|p| p.number == number);
399                let words = pin.map_or("unspecified", |p| type_words(type_index(&p.electrical_type)));
400                let pin_name = pin
401                    .map(|p| p.name.as_str())
402                    .filter(|n| !n.is_empty() && *n != "~" && **n != number)
403                    .map(|n| format!(" ({n})"))
404                    .unwrap_or_default();
405                out.push(ErcFinding {
406                    severity: ErcSeverity::Error,
407                    kind: ErcKind::PinNotConnected,
408                    message: format!("{}.{number}{pin_name}, {words}, is not connected", c.reference),
409                    at: tip(component, &number),
410                    pins: vec![format!("{}.{number}", c.reference)],
411                    fix: Some(ErcFix::MarkNoConnect(vec![Terminal {
412                        component,
413                        pin: number.clone(),
414                    }])),
415                });
416            }
417        }
418        // A gate of a part placed as gates that has no placement.
419        // A sheet's parts off the board are no part of the board's nets.
420        for c in self.components.iter().filter(|c| self.on_board(c)) {
421            if c.gates.is_empty() {
422                continue;
423            }
424            for gate in (1..=c.symbol.gate_count()).filter(|&g| gate_missing(c, g)) {
425                let pins: Vec<_> = c.symbol.pins.iter().filter(|p| p.gate == gate).collect();
426                if pins.is_empty() {
427                    continue;
428                }
429                let power = pins.iter().any(|p| p.electrical_type == "power_in");
430                out.push(ErcFinding {
431                    severity: if power { ErcSeverity::Error } else { ErcSeverity::Warning },
432                    kind: ErcKind::UnitMissing,
433                    message: format!(
434                        "{} is not placed{}: its pins {} are on no sheet",
435                        c.gate_reference(gate),
436                        if power { ", so the part has no power" } else { "" },
437                        pins.iter().map(|p| p.number.as_str()).collect::<Vec<_>>().join(", ")
438                    ),
439                    at: c.at,
440                    pins: pins.iter().map(|p| format!("{}.{}", c.reference, p.number)).collect(),
441                    fix: None,
442                });
443            }
444        }
445        let mut seen: BTreeMap<&str, Vec<&crate::Component>> = BTreeMap::new();
446        // A sheet's parts off the board are no part of the board's nets.
447        for c in self.components.iter().filter(|c| self.on_board(c)) {
448            seen.entry(c.reference.as_str()).or_default().push(c);
449        }
450        for (reference, parts) in seen {
451            if parts.len() > 1 {
452                out.push(ErcFinding {
453                    severity: ErcSeverity::Error,
454                    kind: ErcKind::DuplicateReference,
455                    message: format!("{} parts are called {reference}", parts.len()),
456                    at: parts[1].at,
457                    pins: vec![],
458                    fix: None,
459                });
460            }
461        }
462        out.extend(self.dangling_wire_ends());
463        out.sort_by(|a, b| (a.severity, a.at.y, a.at.x).cmp(&(b.severity, b.at.y, b.at.x)));
464        out
465    }
466    /// A wire end that touches no pin, no other wire, no junction and no label.
467    fn dangling_wire_ends(&self) -> Vec<ErcFinding> {
468        let mut anchors: BTreeSet<Point> = self.junctions.iter().copied().collect();
469        anchors.extend(self.labels.iter().map(|l| l.at));
470        // A sheet's parts off the board are no part of the board's nets.
471        for c in self.components.iter().filter(|c| self.on_board(c)) {
472            anchors.extend(c.symbol.pins.iter().map(|p| c.pin_at(p)));
473        }
474        let mut out = vec![];
475        for (i, w) in self.wires.iter().enumerate() {
476            // A harness wire joins two pins by its terminals; it is no net. A
477            // sub-board's nets are checked in that board's own document.
478            if self.is_harness(w) || self.zone_of_net(w.id).is_some() {
479                continue;
480            }
481            for end in [w.a, w.b] {
482                let touches = anchors.contains(&end)
483                    || self.wires.iter().enumerate().any(|(j, other)| {
484                        j != i
485                            && !self.is_harness(other)
486                            && other
487                                .points()
488                                .windows(2)
489                                .any(|s| crate::on_segment(end, s[0], s[1]))
490                    });
491                if !touches {
492                    out.push(ErcFinding {
493                        severity: ErcSeverity::Warning,
494                        kind: ErcKind::DanglingWire,
495                        message: format!(
496                            "A wire ends at ({:.2}, {:.2}) mm on nothing",
497                            end.x as f64 / 1000.,
498                            end.y as f64 / 1000.
499                        ),
500                        at: end,
501                        pins: vec![],
502                        fix: None,
503                    });
504                }
505            }
506        }
507        out
508    }
509    /// Make the edit a finding offers.
510    pub fn apply_erc_fix(&mut self, fix: &ErcFix) {
511        match fix {
512            ErcFix::MarkNoConnect(pins) => {
513                for t in pins {
514                    if !self.no_connects.contains(t) {
515                        self.no_connects.push(t.clone());
516                    }
517                }
518            }
519            ErcFix::RemoveNoConnect(t) => self.no_connects.retain(|n| n != t),
520            ErcFix::AddPowerFlag(t) => {
521                if !self.power_flags.contains(t) {
522                    self.power_flags.push(t.clone());
523                }
524            }
525        }
526    }
527}
528/// Whether gate `gate` of `c` has no placement although `c` places its gates apart.
529/// A component drawn whole (no gate placements) misses none.
530fn gate_missing(c: &crate::Component, gate: u32) -> bool {
531    gate > 0 && !c.gates.is_empty() && c.symbol.gate_count() > 1 && c.gate(gate).is_none()
532}