BREP_ecad_core 0.1.0

Schematic, wiring diagram, and board documents, symbol import, and connectivity, with no UI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
//! Test fixtures: the KiCad starter symbols and a footprint generator that gives a
//! test component pads from its package name.
//!
//! Neither ships. Symbols and pads come from parts (plan decisions 3 and 10), so no
//! product code reads this module: it compiles only for this crate's own tests and
//! for a crate that asks for it with the `fixtures` feature, as a dev-dependency.
//! Cargo does not unify a dev-dependency's features into a normal build, so the
//! two CC-BY-SA KiCad files below are in no shipped binary.
//!
//! The generator is the one eCAD's board flow used before parts carried their pads,
//! kept so that the autorouter and fabrication tests route and plot exactly the
//! boards they always have. Its geometry follows IPC nominal land patterns closely
//! enough for layout and routing: measured against KiCad 9.0.0 by pad number, it
//! matches SOIC-8 and 0805 exactly, is within 0.012 mm in position and 0.075 mm in
//! size on QFN-32, and is 0.2 mm out on SOT-23.
use crate::board::{Footprint, Pad, PadShape};
use crate::footprint::pin_numbers;
use crate::{Document, Point, Symbol};
use std::collections::BTreeSet;

/// The KiCad starter symbols: `Device` (`R`, `C`, `LED`, `D`) and
/// `Connector_Generic` (`Conn_01x02`, `Conn_01x04`), from KiCad 9.0.0.
/// `assets/kicad/PROVENANCE.json` records the selection and `LICENSE.md` the terms.
pub fn kicad_symbols() -> Vec<Symbol> {
    [
        ("Device", include_str!("../assets/kicad/Device.kicad_sym")),
        (
            "Connector_Generic",
            include_str!("../assets/kicad/Connector_Generic.kicad_sym"),
        ),
    ]
    .into_iter()
    .flat_map(|(name, text)| {
        crate::kicad::import_library(text, name)
            .expect("valid bundled library")
            .symbols
    })
    .collect()
}

/// One of [`kicad_symbols`] by its library id, such as `Device:R`.
pub fn kicad_symbol(library_id: &str) -> Symbol {
    kicad_symbols()
        .into_iter()
        .find(|s| s.library_id == library_id)
        .unwrap_or_else(|| panic!("no fixture symbol {library_id}"))
}

/// Give every component that needs a footprint and has no pads the pads its
/// symbol's `Footprint` property names, as the board flow did before parts carried
/// pads, so [`Document::sync_board`] places it.
pub fn with_pads(document: &mut Document) {
    for c in &mut document.components {
        if c.pads.is_none() && crate::board::needs_footprint(c) {
            c.pads = Some(pads_for(&c.symbol));
        }
    }
}

type Parts = (Vec<Pad>, Vec<Vec<Point>>);

fn mm(v: f64) -> i32 {
    (v * 1000.).round() as i32
}
fn at(x: f64, y: f64) -> Point {
    Point::new(mm(x), mm(y))
}
fn smd(number: usize, x: f64, y: f64, w: f64, h: f64) -> Pad {
    Pad {
        number: number.to_string(),
        at: at(x, y),
        size: at(w, h),
        shape: PadShape::Rect,
        drill: None,
        plated: true,
    }
}
/// Through-hole pad; pin 1 is square so orientation is visible.
fn tht(number: usize, x: f64, y: f64, w: f64, h: f64, drill: f64) -> Pad {
    Pad {
        number: number.to_string(),
        at: at(x, y),
        size: at(w, h),
        shape: match (number, w == h) {
            (1, _) => PadShape::Rect,
            (_, true) => PadShape::Circle,
            (_, false) => PadShape::Oval,
        },
        drill: Some(mm(drill)),
        plated: true,
    }
}
fn outline(w: f64, h: f64) -> Vec<Point> {
    let (x, y) = (w / 2., h / 2.);
    vec![at(-x, -y), at(x, -y), at(x, y), at(-x, y), at(-x, -y)]
}
fn circle_outline(d: f64) -> Vec<Point> {
    (0..=24)
        .map(|i| {
            let t = std::f64::consts::TAU * f64::from(i) / 24.;
            at(d / 2. * t.cos(), d / 2. * t.sin())
        })
        .collect()
}
/// The first positive decimal number immediately following `key`.
fn number_after(name: &str, key: &str) -> Option<f64> {
    let mut rest = name;
    while let Some(i) = rest.find(key) {
        rest = &rest[i + key.len()..];
        let digits: String = rest
            .chars()
            .take_while(|c| c.is_ascii_digit() || *c == '.')
            .collect();
        if let Ok(v) = digits.parse::<f64>()
            && v > 0.
            && v < 1000.
        {
            return Some(v);
        }
    }
    None
}
/// A `<prefix><w>x<h>mm` token, e.g. `5x5mm` or `EP3.45x3.45mm`.
fn dims(name: &str, prefix: &str) -> Option<(f64, f64)> {
    name.split('_').find_map(|t| {
        let (w, h) = t
            .strip_prefix(prefix)?
            .strip_suffix("mm")?
            .split_once('x')?;
        let (w, h) = (w.parse::<f64>().ok()?, h.parse::<f64>().ok()?);
        (w > 0. && h > 0. && w < 1000. && h < 1000.).then_some((w, h))
    })
}
/// Family token split into kind and pin count: `QFN-32-1EP` → (`QFN`, 32).
fn family(name: &str) -> Option<(&str, usize)> {
    let mut parts = name.split('_').next()?.split('-');
    let kind = parts.next()?;
    let count = parts.next()?.parse().ok()?;
    (count > 0 && count <= 1024).then_some((kind, count))
}

/// A footprint generated from a KiCad-style name such as
/// `Package_SO:SOIC-8_3.9x4.9mm_P1.27mm` or `R_0805_2012Metric`.
pub fn package(name: &str) -> Option<Footprint> {
    let short = name.trim().rsplit(':').next().unwrap_or(name);
    let (pads, silk) = chip(short)
        .or_else(|| sot(short))
        .or_else(|| sod(short))
        .or_else(|| gullwing(short))
        .or_else(|| no_lead(short))
        .or_else(|| dip(short))
        .or_else(|| header(short))
        .or_else(|| axial(short))
        .or_else(|| radial(short))
        .or_else(|| to_package(short))?;
    Some(Footprint {
        name: name.trim().into(),
        pads,
        silk,
        model: None,
    })
}

/// Imperial code, pad width, pad height, pad centre offset, body length, body width.
const CHIPS: &[(&str, f64, f64, f64, f64, f64)] = &[
    ("0201", 0.4, 0.4, 0.34, 0.6, 0.3),
    ("0402", 0.54, 0.64, 0.51, 1.0, 0.5),
    ("0603", 0.8, 0.95, 0.825, 1.6, 0.8),
    ("0805", 1.025, 1.4, 0.9125, 2.0, 1.25),
    ("1206", 1.125, 1.75, 1.4625, 3.2, 1.6),
    ("1210", 1.125, 2.65, 1.4625, 3.2, 2.5),
    ("2512", 1.525, 3.35, 3.1, 6.3, 3.2),
];
fn chip(name: &str) -> Option<Parts> {
    if name.contains("Axial") || name.contains("Radial") {
        return None;
    }
    let &(_, w, h, x, length, width) = name
        .split('_')
        .find_map(|t| CHIPS.iter().find(|c| c.0 == t))?;
    Some((
        vec![smd(1, -x, 0., w, h), smd(2, x, 0., w, h)],
        vec![outline(length, width)],
    ))
}
fn sot(name: &str) -> Option<Parts> {
    let (w, h, x, p) = (1.325, 0.6, 1.1375, 0.95);
    let body = vec![outline(1.6, 2.9)];
    let pads = match name.split('_').next()? {
        "SOT-23" | "SOT-23-3" => vec![
            smd(1, -x, -p, w, h),
            smd(2, -x, p, w, h),
            smd(3, x, 0., w, h),
        ],
        "SOT-23-5" => vec![
            smd(1, -x, -p, w, h),
            smd(2, -x, 0., w, h),
            smd(3, -x, p, w, h),
            smd(4, x, p, w, h),
            smd(5, x, -p, w, h),
        ],
        "SOT-23-6" => vec![
            smd(1, -x, -p, w, h),
            smd(2, -x, 0., w, h),
            smd(3, -x, p, w, h),
            smd(4, x, p, w, h),
            smd(5, x, 0., w, h),
            smd(6, x, -p, w, h),
        ],
        "SOT-223" | "SOT-223-3" => {
            let mut pads: Vec<Pad> = (0..3)
                .map(|i| smd(i + 1, -3.15, (i as f64 - 1.) * 2.3, 2., 1.5))
                .collect();
            let mut tab = smd(4, 3.15, 0., 2., 3.8);
            if name.contains("TabPin2") {
                tab.number = "2".into();
            }
            pads.push(tab);
            return Some((pads, vec![outline(3.5, 6.5)]));
        }
        _ => return None,
    };
    Some((pads, body))
}
fn sod(name: &str) -> Option<Parts> {
    let (x, w, h, length, width) = if name.contains("SOD-123") {
        (1.65, 0.9, 1.2, 2.7, 1.6)
    } else if name.contains("SOD-323") {
        (1.1, 0.6, 0.45, 1.7, 1.25)
    } else if name.contains("SOD-523") {
        (0.7, 0.6, 0.5, 1.2, 0.8)
    } else if name.ends_with("_SMA") || name.contains("_SMA_") {
        (2., 2.5, 1.7, 4.3, 2.6)
    } else if name.ends_with("_SMB") || name.contains("_SMB_") {
        (2.15, 2.5, 2.3, 4.3, 3.6)
    } else if name.ends_with("_SMC") || name.contains("_SMC_") {
        (3.4, 3.3, 3.2, 6.9, 5.9)
    } else {
        return None;
    };
    Some((
        vec![smd(1, -x, 0., w, h), smd(2, x, 0., w, h)],
        vec![outline(length, width)],
    ))
}
/// Pads around a package: left side top to bottom, then (for four-sided parts) the
/// bottom left to right, the right bottom to top, and the top right to left.
fn perimeter(count: usize, sides: usize, pitch: f64, c: (f64, f64), land: (f64, f64)) -> Vec<Pad> {
    let per_side = count / sides;
    let offset = |i: usize| (i as f64 - (per_side as f64 - 1.) / 2.) * pitch;
    let (len, width) = land;
    let mut pads = vec![];
    for i in 0..per_side {
        pads.push(smd(pads.len() + 1, -c.0, offset(i), len, width));
    }
    if sides == 4 {
        for i in 0..per_side {
            pads.push(smd(pads.len() + 1, offset(i), c.1, width, len));
        }
    }
    for i in 0..per_side {
        pads.push(smd(pads.len() + 1, c.0, -offset(i), len, width));
    }
    if sides == 4 {
        for i in 0..per_side {
            pads.push(smd(pads.len() + 1, -offset(i), -c.1, width, len));
        }
    }
    pads
}
fn with_exposed_pad(name: &str, mut pads: Vec<Pad>, count: usize) -> Vec<Pad> {
    if let Some((w, h)) = dims(name, "EP") {
        pads.push(smd(count + 1, 0., 0., w, h));
    }
    pads
}
/// Gull-wing small-outline and quad flat packages.
fn gullwing(name: &str) -> Option<Parts> {
    let (kind, count) = family(name)?;
    let (sides, default_width, default_pitch, lead_extra) = match kind {
        "SOIC" | "SO" => (2, 3.9, 1.27, 2.1),
        "TSSOP" | "HTSSOP" | "VSSOP" | "TSOP" => (2, 4.4, 0.65, 2.0),
        "MSOP" => (2, 3.0, 0.65, 1.9),
        "SSOP" | "QSOP" => (2, 5.3, 0.65, 2.5),
        "LQFP" | "TQFP" | "QFP" | "PQFP" | "MQFP" | "VQFP" => (4, 0., 0.5, 2.0),
        _ => return None,
    };
    if count % sides != 0 {
        return None;
    }
    let pitch = number_after(name, "_P").unwrap_or(default_pitch);
    let row = (count / sides) as f64 * pitch;
    let (width, length) = dims(name, "").unwrap_or(if sides == 4 {
        (row + 1.5, row + 1.5)
    } else {
        (default_width, row + 0.5)
    });
    let (len, land_width, toe) = if sides == 4 {
        (1.475, (pitch * 0.6).min(0.55), 0.4)
    } else if pitch >= 1. {
        (1.95, (pitch * 0.62).min(0.6), 0.45)
    } else {
        (1.475, (pitch * 0.62).min(0.6), 0.4)
    };
    let centre = |body: f64| (body + lead_extra) / 2. - len / 2. + toe;
    let pads = perimeter(
        count,
        sides,
        pitch,
        (centre(width), centre(length)),
        (len, land_width),
    );
    Some((
        with_exposed_pad(name, pads, count),
        vec![outline(width, length)],
    ))
}
/// Quad and dual flat no-lead packages.
fn no_lead(name: &str) -> Option<Parts> {
    let (kind, count) = family(name)?;
    let sides = if kind.ends_with("QFN") {
        4
    } else if kind.ends_with("DFN") {
        2
    } else {
        return None;
    };
    if count % sides != 0 {
        return None;
    }
    let pitch = number_after(name, "_P").unwrap_or(0.5);
    let row = (count / sides) as f64 * pitch + 1.;
    let (width, length) = dims(name, "").unwrap_or((row, row));
    let pads = perimeter(
        count,
        sides,
        pitch,
        (width / 2. - 0.05, length / 2. - 0.05),
        // Short enough that corner pads on adjacent sides keep 0.2 mm clearance.
        (0.8, (pitch * 0.5).min(0.35)),
    );
    Some((
        with_exposed_pad(name, pads, count),
        vec![outline(width, length)],
    ))
}
fn dip(name: &str) -> Option<Parts> {
    let (kind, count) = family(name)?;
    let pitch = match kind {
        "DIP" | "PDIP" | "CERDIP" => 2.54,
        "SDIP" => 1.778,
        _ => return None,
    };
    if count % 2 != 0 {
        return None;
    }
    let row = number_after(name, "_W").unwrap_or(7.62);
    let per_side = count / 2;
    let offset = |i: usize| (i as f64 - (per_side as f64 - 1.) / 2.) * pitch;
    let size = if pitch < 2. { 1.4 } else { 1.6 };
    let mut pads = vec![];
    for i in 0..per_side {
        pads.push(tht(i + 1, -row / 2., offset(i), size, size, 0.8));
    }
    for i in 0..per_side {
        pads.push(tht(per_side + i + 1, row / 2., -offset(i), size, size, 0.8));
    }
    Some((
        pads,
        vec![outline(row - 1.27, per_side as f64 * pitch + 0.5)],
    ))
}
/// Pin headers, sockets, and other connectors named with `<columns>x<rows>_P<pitch>mm`.
fn header(name: &str) -> Option<Parts> {
    let (columns, rows) = name.split('_').find_map(|t| {
        let (a, b) = t.split_once('x')?;
        let digits = |s: &str| !s.is_empty() && s.bytes().all(|c| c.is_ascii_digit());
        (digits(a) && digits(b)).then(|| (a.parse::<usize>().ok(), b.parse::<usize>().ok()))
    })?;
    let (columns, rows) = (columns?, rows?);
    if columns == 0 || rows == 0 || columns > 4 || rows > 200 {
        return None;
    }
    let pitch = number_after(name, "_P")?;
    let (size, drill) = if pitch >= 2.5 {
        (1.7, 1.0)
    } else if pitch >= 2. {
        (1.35, 0.8)
    } else if pitch >= 1.27 {
        (1.0, 0.65)
    } else {
        (pitch * 0.75, pitch * 0.4)
    };
    let centre = |i: usize, n: usize| (i as f64 - (n as f64 - 1.) / 2.) * pitch;
    let pads = (0..columns * rows)
        .map(|k| {
            tht(
                k + 1,
                centre(k % columns, columns),
                centre(k / columns, rows),
                size,
                size,
                drill,
            )
        })
        .collect();
    Some((
        pads,
        vec![outline(columns as f64 * pitch, rows as f64 * pitch)],
    ))
}
fn axial(name: &str) -> Option<Parts> {
    if !(name.contains("Axial") || name.contains("_DO-") || name.starts_with("DO-")) {
        return None;
    }
    let pitch = number_after(name, "_P").unwrap_or(10.16);
    let (size, drill) = if name.contains("DO-201") || name.contains("DO-27") {
        (2.8, 1.5)
    } else if name.contains("DO-41") || name.contains("DO-15") {
        (2.2, 1.1)
    } else {
        (1.6, 0.8)
    };
    let length = number_after(name, "_L").unwrap_or(pitch * 0.6);
    let diameter = number_after(name, "_D").unwrap_or(2.5);
    Some((
        vec![
            tht(1, -pitch / 2., 0., size, size, drill),
            tht(2, pitch / 2., 0., size, size, drill),
        ],
        vec![outline(length.min(pitch - size), diameter)],
    ))
}
fn radial(name: &str) -> Option<Parts> {
    if !(name.contains("Radial")
        || name.contains("Disc_")
        || name.starts_with("C_Rect")
        || name.starts_with("LED_D"))
    {
        return None;
    }
    let pitch = number_after(name, "_P").unwrap_or(2.54);
    let (size, drill) = if pitch >= 5. { (2., 1.) } else { (1.6, 0.8) };
    let silk = number_after(name, "_D").map_or_else(|| outline(pitch + 2.5, 2.5), circle_outline);
    Some((
        vec![
            tht(1, -pitch / 2., 0., size, size, drill),
            tht(2, pitch / 2., 0., size, size, drill),
        ],
        vec![silk],
    ))
}
fn to_package(name: &str) -> Option<Parts> {
    let row = |count: usize, pitch: f64, w: f64, h: f64, drill: f64| -> Vec<Pad> {
        (0..count)
            .map(|i| {
                tht(
                    i + 1,
                    (i as f64 - (count as f64 - 1.) / 2.) * pitch,
                    0.,
                    w,
                    h,
                    drill,
                )
            })
            .collect()
    };
    if name.starts_with("TO-92") {
        Some((row(3, 1.27, 1.05, 1.5, 0.75), vec![outline(4.8, 3.8)]))
    } else if name.starts_with("TO-220") || name.starts_with("TO-247") || name.starts_with("TO-3P")
    {
        // `TO-220-3_Vertical`: the pin count is the third dash-separated field.
        let count = name
            .split('_')
            .next()
            .and_then(|f| f.split('-').nth(2))
            .and_then(|n| n.parse::<usize>().ok())
            .map_or(3, |n| n.clamp(2, 15));
        let pitch = if name.starts_with("TO-220") {
            2.54
        } else {
            5.45
        };
        let (w, h, drill) = if pitch < 3. {
            (1.905, 2., 1.1)
        } else {
            (2.5, 3.5, 1.4)
        };
        let body = count as f64 * pitch + 2.;
        Some((row(count, pitch, w, h, drill), vec![outline(body, 4.6)]))
    } else if name.contains("HC49") {
        Some((row(2, 4.88, 1.5, 1.5, 0.8), vec![outline(11., 4.7)]))
    } else {
        None
    }
}

/// A package sized from the symbol's pin count, with pads numbered by its pins.
fn fallback(symbol: &Symbol) -> Footprint {
    let pins = pin_numbers(symbol);
    let n = pins.len();
    let connector = symbol.library_id.starts_with("Connector")
        || matches!(symbol.reference_prefix.as_str(), "J" | "P" | "CN" | "X");
    let name = if n == 0 {
        String::new()
    } else if connector || n == 1 {
        if n <= 40 {
            format!("PinHeader_1x{n:02}_P2.54mm_Vertical")
        } else {
            format!("PinHeader_2x{:02}_P2.54mm_Vertical", n.div_ceil(2))
        }
    } else {
        match n {
            2 => {
                let kind = match symbol.reference_prefix.as_str() {
                    "C" => "C",
                    "L" => "L",
                    "D" => "D",
                    "LED" | "LD" => "LED",
                    "F" => "Fuse",
                    _ => "R",
                };
                format!("{kind}_0805_2012Metric")
            }
            3 => "SOT-23".into(),
            4..=28 => {
                let count = n.next_multiple_of(2);
                format!(
                    "SOIC-{count}_3.9x{:.2}mm_P1.27mm",
                    (count / 2) as f64 * 1.27 + 0.5
                )
            }
            29..=100 => {
                let count = n.next_multiple_of(4);
                let body = (count / 4) as f64 * 0.8 + 1.2;
                format!("LQFP-{count}_{body:.1}x{body:.1}mm_P0.8mm")
            }
            _ => {
                let count = n.next_multiple_of(4);
                let body = (count / 4) as f64 * 0.5 + 1.5;
                format!("LQFP-{count}_{body:.1}x{body:.1}mm_P0.5mm")
            }
        }
    };
    let mut footprint = package(&name).unwrap_or_default();
    footprint.name = format!("Generated:{}", if n == 0 { "NoPins" } else { &name });
    footprint.pads.truncate(n);
    for (pad, pin) in footprint.pads.iter_mut().zip(&pins) {
        pad.number = pin.clone();
    }
    footprint
}

/// Generate the named footprint. When the pad numbers do not cover the symbol's pins
/// but the counts agree, pads are renumbered: the footprint's pad order is matched to
/// the pins' natural order. The flag reports whether every pin now has a pad.
fn resolve(name: &str, symbol: &Symbol) -> Option<(Footprint, bool)> {
    let mut footprint = package(name.trim())?;
    let pins = pin_numbers(symbol);
    // Distinct pad numbers in the order the footprint lists them.
    let numbers = |f: &Footprint| -> Vec<String> {
        let mut seen = BTreeSet::new();
        f.pads
            .iter()
            .filter(|p| !p.number.is_empty() && seen.insert(p.number.clone()))
            .map(|p| p.number.clone())
            .collect()
    };
    let covered = |f: &Footprint| {
        let n = numbers(f);
        pins.iter().all(|p| n.contains(p))
    };
    if !covered(&footprint) {
        let existing = numbers(&footprint);
        if existing.len() == pins.len() {
            for pad in &mut footprint.pads {
                if let Some(i) = existing.iter().position(|n| *n == pad.number) {
                    pad.number = pins[i].clone();
                }
            }
        }
    }
    let ok = covered(&footprint);
    Some((footprint, ok))
}

/// The footprint named by the symbol's `Footprint` property when it can be generated
/// and covers every pin; otherwise a pin-count fallback.
pub fn pads_for(symbol: &Symbol) -> Footprint {
    symbol
        .properties
        .get("Footprint")
        .filter(|n| !n.trim().is_empty())
        .and_then(|name| resolve(name, symbol))
        .filter(|(_, covered)| *covered)
        .map_or_else(|| fallback(symbol), |(f, _)| f)
}