dune-pic 0.2.0

SPICE netlist extraction from rpic (pic) schematic figures
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
//! SPICE netlist extraction from rpic figures (PLAN §2.5; D-0003,
//! D-0004, D-0019, D-0020).
//!
//! A figure is ordinary pic, compiled by [`rpic_core`] as a library,
//! with the `spice.pic` prelude (embedded; `src/spice.pic`)
//! loaded after rpic's std circuit library. The prelude wraps every
//! D-0019 element in a labeled block:
//!
//! ```text
//! .PS
//! spice = 1
//! In: (0,1); Out: (2,1)
//! V1: vsource(In, (0,0), DC 5)
//! R1: resistor(In, Out, 1k)
//! C1: capacitor(Out, (2,0), 1u)
//! line from C1.N to V1.N; ground(V1.N)
//! .tran 10u 5m
//! .PE
//! ```
//!
//! extracts to `V1 In 0 DC 5`, `R1 In Out 1k`, `C1 Out 0 1u`,
//! `.tran 10u 5m`, `.end`.
//!
//! Conventions (the contract between the prelude and this crate):
//!
//! * **refdes = block label**; its first letter picks the card type
//!   (D-0004 §1), restricted to the D-0019 set `R C L V I D Q M J S W X`
//!   plus the transmission lines `T` (ideal) and `O` (LTRA), the
//!   controlled sources `E F G H`, the mutual inductance `K`
//!   (D-0026) and the MESFET `Z`;
//! * **pins** are `circle invis rad 0` shapes labeled `P`/`N`,
//!   `C`/`B`/`E` (+ the optional substrate `S`), `D`/`G`/`S`/`B`,
//!   `Inp`/`Inm`/`Out` (the op-amp `X`), `P1` … `PN` (a generic `X`
//!   of N nodes), `Cp`/`Cn`, `P1`/`N1`/`P2`/`N2` that
//!   are direct children of the element block (D-0020 §c); a `K`
//!   block has no pins, only a `Mutual` marker;
//! * **value/model = the macro argument after the pin positions**
//!   (D-0004 §2: the 3rd of a two-terminal, the 5th of the four-point
//!   `E`/`G`, the (N+1)th of a generic `X` of N pins, the 2nd of an
//!   element centered on an `At` anchor; all
//!   three arguments of a `K`, `L1 L2 k`), read verbatim from the call
//!   in the user's source (`1e-9` stays `1e-9`). The prelude also draws it
//!   (the first text shape in the block); that drawing is presentation,
//!   read only as a fallback when the block has no usable call (an
//!   inline block, or a wrapper macro whose arguments are not the
//!   element's) and, normalized by pic, to check that the call's
//!   argument really is the element's value;
//! * **wires** are the visible `line`/`arrow` paths outside element
//!   and ground blocks; **dots** are explicit junctions; connectivity
//!   rules are in [`connect`];
//! * **nets** (D-0004 §3): a `ground(P)` block makes node `0`; a named
//!   place (`Vout: (2,1)`, `Vin: R1.P`) that coincides with a net
//!   names it — places that share a label are one SPICE node; the rest
//!   are `n1, n2, …` in order of first appearance (lowest shape index);
//! * **directives** (D-0004 §4): column-1 `.` lines (rpic's
//!   `Drawing.passthrough`, the troff rule), with their column-1 `+`
//!   continuations, pass through to the netlist in source order; a user
//!   `.end` is dropped and one is appended.
//!
//! The figure must set `spice = 1` (D-0004 §5) or extraction refuses.

#![forbid(unsafe_code)]

mod connect;
mod spans;

use std::collections::{BTreeMap, HashMap, HashSet};
use std::fmt;
use std::ops::Range;

use rpic_core::ir::{Drawing, MacroCall, PlaceInfo, Shape};
use rpic_core::{CompileOptions, IncludePolicy};

use crate::connect::{Pt, UnionFind, join_geometry};

/// The embedded dune prelude (`src/spice.pic`, inside the crate so
/// the packaged crate — the Python sdist, the R vendor tarball —
/// carries it).
pub const PRELUDE: &str = include_str!("spice.pic");

/// Default snap tolerance, in pic inches (PLAN §2.5).
pub const DEFAULT_SNAP: f64 = 1e-3;

/// Marker label of the prelude's `ground(P)` block.
const GROUND_MARKER: &str = "Gnd";
/// Marker label of the anchor of centered elements, whose value is the
/// 2nd macro argument instead of the 3rd.
const ANCHOR_MARKER: &str = "At";
/// Marker of the prelude's `coupling(L1, L2, k)` block (a `K` card,
/// which has no pins).
const COUPLING_MARKER: &str = "Mutual";
/// Every pin-marker label the prelude uses on elements, plus the
/// `At` anchor of centered elements and the coupling marker.
const ELEMENT_MARKERS: &[&str] = &[
    "P", "N", "Cp", "Cn", "C", "B", "E", "D", "G", "S", "Inp", "Inm", "Out", "P1", "N1", "P2",
    "N2", "P3", "P4", "P5", "P6", "P7", "At", "Mutual",
];
/// Pins of a `Q` drawn with its substrate (`npn4`/`pnp4`).
const BJT4_PINS: &[&str] = &["C", "B", "E", "S"];
/// Pins of a generic subcircuit instance (`subckt2` … `subckt7`, an
/// `X` card with N nodes): the first N of these, in card order.
const SUBCKT_PINS: &[&str] = &["P1", "P2", "P3", "P4", "P5", "P6", "P7"];
/// Marker of a block whose drawn text is a display, not the value.
const DISPLAY_MARKER: &str = "Disp";
/// Prelude macros that take an optional display text after the
/// value/model, drawn instead of it (two-terminals, `vcvs`/`vccs` and
/// the elements centered on an `At` anchor).
const DISPLAY_MACROS: &[&str] = &[
    "resistor",
    "capacitor",
    "inductor",
    "diode",
    "vsource",
    "acsource",
    "battery",
    "isource",
    "cccs",
    "ccvs",
    "vcvs",
    "vccs",
    "npn",
    "pnp",
    "npn4",
    "pnp4",
    "nmos",
    "pmos",
    "nmos4",
    "pmos4",
    "njfet",
    "pjfet",
    "nmes",
    "pmes",
    "opamp",
    "subckt2",
    "subckt3",
    "subckt4",
    "subckt5",
    "subckt6",
    "subckt7",
];
/// The supported card letters, for messages.
const LETTERS: &str = "R C L V I D Q M J Z S W X T O E F G H K";

/// Options for [`extract`].
#[derive(Debug, Clone, Copy)]
pub struct ExtractOptions<'a> {
    /// Distance (pic inches) under which two terminals are the same
    /// point. Default [`DEFAULT_SNAP`].
    pub snap: f64,
    /// Prelude loaded after rpic's std circuit library; `None` uses the
    /// embedded [`PRELUDE`].
    pub prelude: Option<&'a str>,
}

impl Default for ExtractOptions<'_> {
    fn default() -> Self {
        Self {
            snap: DEFAULT_SNAP,
            prelude: None,
        }
    }
}

/// A position in the figure source (1-based line/column, end
/// exclusive).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PicSpan {
    /// `None` = the user's figure; `Some("spice.pic")` = the prelude;
    /// `Some("circuits")` = rpic's std library.
    pub file: Option<String>,
    pub line: u32,
    pub col: u32,
    pub end_col: u32,
}

impl fmt::Display for PicSpan {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(file) = &self.file {
            write!(f, "{file}:")?;
        }
        write!(f, "{}:{}", self.line, self.col)
    }
}

/// Diagnostic severity.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PicSeverity {
    /// The netlist is emitted but is wrong or incomplete (an element
    /// was skipped or lacks its value).
    Error,
    /// The netlist is emitted and probably what was meant.
    Warning,
}

/// What a [`PicDiagnostic`] is about.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PicDiagKind {
    /// An element pin no other element pin (or ground) connects to.
    DanglingPin,
    /// Wires (or a named node) that reach no element pin.
    FloatingNet,
    /// An element block with no (or an empty) value text.
    MissingValue,
    /// Two elements with the same refdes (SPICE names are
    /// case-insensitive).
    DuplicateRefdes,
    /// A refdes whose first letter is outside the supported set.
    UnknownElement,
    /// An element block without one of the pins its letter needs.
    MissingPin,
    /// An element block without a label.
    UnlabeledElement,
    /// One net carrying two different names (or a name and ground).
    NodeNameConflict,
    /// Something in the source that defeats the prelude.
    Prelude,
}

/// A structured extraction diagnostic.
#[derive(Debug, Clone, PartialEq)]
pub struct PicDiagnostic {
    pub severity: PicSeverity,
    pub kind: PicDiagKind,
    pub message: String,
    /// Where in the figure, when known.
    pub span: Option<PicSpan>,
}

impl fmt::Display for PicDiagnostic {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let sev = match self.severity {
            PicSeverity::Error => "error",
            PicSeverity::Warning => "warning",
        };
        match &self.span {
            Some(s) => write!(f, "{s}: {sev}: {}", self.message),
            None => write!(f, "{sev}: {}", self.message),
        }
    }
}

/// Why no netlist could be produced at all.
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
pub enum PicError {
    /// rpic rejected the figure.
    #[error("pic: {message}")]
    Compile {
        message: String,
        span: Option<PicSpan>,
    },
    /// The figure does not opt in with `spice = 1` (D-0004 §5).
    #[error("figure not marked `spice = 1`; dune-pic only extracts figures that opt in")]
    NotMarked,
}

/// One element's shapes in the compiled drawing (ids `sN` of the SVG).
#[derive(Debug, Clone, PartialEq)]
pub struct ElementOverlay {
    pub refdes: String,
    /// Half-open range of shape indices of the element's block.
    pub shapes: Range<usize>,
    /// The element's terminals, in card order (the nodes of its card);
    /// empty for a `K`, which has none.
    pub pins: Vec<PinOverlay>,
    /// Where the element's value/model argument is in the user's
    /// source — the text an editor replaces to write a new value back
    /// (issue #17).
    ///
    /// `Some` only when the card's value is that argument of a call to
    /// one of the prelude's own element macros (`R1: resistor(A, B,
    /// 1k)`), written in the user's figure. `None` when there is none
    /// to point at: an element without a value argument (`vsource(A,
    /// B)`), a `K` (`coupling(L1, L2, k)` spreads its card over three
    /// arguments), an inline block, and every element whose outermost
    /// call is a user wrapper macro — the value then comes from the
    /// drawn fallback or from a wrapper argument, and neither is a span
    /// an edit can be trusted to land in. A display text (the argument
    /// after the value) never changes this: the span stays the value's.
    pub value: Option<ValueSpanOverlay>,
    /// The alterable parameters spelled inside [`Self::value`], in
    /// source order, named as `alter(refdes, param, …)` names them
    /// (`dune_core::Circuit::alter`): for `V`/`I` sources `dc`,
    /// `acmag`, `acphase` (each the span of its number only: `AC 1 90`
    /// gives `acmag` = `1` and `acphase` = `90`) and the transient
    /// functions `pulse`, `sin`, `exp`, `pwl`, `sffm`, `trnoise`,
    /// `trrandom` (each the whole spelling, keyword and parentheses
    /// included: `PULSE(0 5 0 1u 1u 10m 20m)`); for `R`/`C`/`L`/`E`/`G`
    /// the principal value (the leading number) and `ic` (`IC=…`,
    /// `C`/`L`); `gain` of an `F`/`H` (`Vname gain`); `area` (the
    /// number after the model, or `AREA=`) and `temp` (`TEMP=`) of a
    /// `D`/`Q`/`J`; `area` of a `Z`; `w`, `l`, `temp` (`W=`…) of an `M`. Only what is
    /// spelled is listed (a source with no `DC` field has no `dc`
    /// entry), and a parameter spelled twice is listed once, at its
    /// last spelling (the one SPICE keeps). Empty when
    /// [`Self::value`] is `None`.
    pub params: Vec<ParamSpanOverlay>,
    /// The parameter `alter(refdes, value)` (empty parameter name)
    /// changes for this element's letter: `resistance`, `capacitance`,
    /// `inductance`, `dc` (`V`/`I`), `gain` (`E`/`F`/`G`/`H`), `area`
    /// (`D`/`Q`/`J`/`Z`); `None` for letters `alter` has no principal for
    /// (`M`, `S`, `W`, `X`, `T`, `O`, `K`). Independent of
    /// [`Self::value`].
    pub principal: Option<String>,
}

/// A range of the user's figure source (never the prelude): 1-based
/// lines and columns, as the diagnostics' [`PicSpan`], from
/// `(line, col)` to `(end_line, end_col)`, end exclusive. Columns
/// count **chars** (Unicode scalar values) from the start of the line —
/// not bytes, not UTF-16 code units: a JavaScript consumer indexes a
/// line by code point (`Array.from(line)`), not by `line[i]`, when the
/// line holds characters outside the BMP. Lines are split at `\n`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PicRange {
    pub line: u32,
    pub col: u32,
    pub end_line: u32,
    pub end_col: u32,
}

/// [`ElementOverlay::value`]: the value argument's range and its text.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValueSpanOverlay {
    /// The range of `text` in the user's source. It spans lines when
    /// the argument is split by `\` continuations.
    pub span: PicRange,
    /// The source text in `span`, verbatim (`4.7k`, `AC 1`, `SIN(0 1
    /// 1k)`; `\` continuations kept). A quoted argument (`"DX"`) gives
    /// the range and text inside the quotes — the card's value.
    pub text: String,
}

/// One entry of [`ElementOverlay::params`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParamSpanOverlay {
    /// The `alter` parameter name (`dc`, `acmag`, `pulse`, …).
    pub name: String,
    /// Its range in the user's source, inside the value's range.
    pub span: PicRange,
    /// The source text in `span`.
    pub text: String,
}

/// The page frame of the SVG [`render_svg`] draws (issue #19): what
/// maps a point of the compiled drawing — [`PinOverlay::x`]/`y`, in
/// pic inches with y up — to SVG user units (the root `viewBox`
/// space, 96 per inch, y down). Exactly:
///
/// ```text
/// sx = (x + origin[0]) · 96
/// sy = (h − (y + origin[1])) · 96
/// ```
///
/// ([`Self::to_svg`]). This is rpic's own frame — the `canvas` of its
/// scene export (`origin` is where the pic origin sits, measured from
/// the page's lower-left corner; `w`/`h` the page size in inches,
/// margins and stroke padding included, so the `viewBox` is `0 0 w·96
/// h·96`), computed here at full precision instead of the scene's six
/// decimals. Note the signs (`+ origin`) and that `rescale` does not
/// enter: the drawing's coordinates, pins included, are already past
/// the whole-picture rescale.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct CanvasOverlay {
    /// Page width and height in inches (`viewBox` = `0 0 w·96 h·96`).
    pub w: f64,
    pub h: f64,
    /// The pic origin, in inches from the page's lower-left corner.
    pub origin: [f64; 2],
    /// The whole-picture rescale factor (`.PS <width>`, `maxpswid`,
    /// `maxpsht`; 1 when none) — informational: the shapes and pins
    /// already carry it.
    pub rescale: f64,
}

impl Default for CanvasOverlay {
    fn default() -> Self {
        Self {
            w: 0.0,
            h: 0.0,
            origin: [0.0, 0.0],
            rescale: 1.0,
        }
    }
}

impl CanvasOverlay {
    /// SVG user units of the drawing point `(x, y)` (pic inches).
    pub fn to_svg(&self, x: f64, y: f64) -> (f64, f64) {
        (
            (x + self.origin[0]) * SVG_PPI,
            (self.h - (y + self.origin[1])) * SVG_PPI,
        )
    }
}

/// rpic's SVG scale, user units per inch (dpic's `dpPPI`).
const SVG_PPI: f64 = 96.0;

/// One terminal of an element: where it is drawn and the net it is on.
///
/// Element pins are invisible markers inside the element's own shapes,
/// so a net whose elements touch pin to pin has no wire of its own in
/// [`NetOverlay::shapes`]; the pins still give a probe target for it.
#[derive(Debug, Clone, PartialEq)]
pub struct PinOverlay {
    /// The pin's prelude name (`P`, `N`, `C`, `B`, `E`, `D`, `G`, `S`,
    /// `Inp`, `Cp`, `P1`, …; D-0020; `P1` … `PN` on a generic `X`).
    pub name: String,
    /// The node name on the card, as in [`NetOverlay::name`].
    pub net: String,
    /// The terminal point, in pic inches, in the frame of the compiled
    /// drawing's shapes (y up, after the whole-picture rescale) — the
    /// frame of rpic's scene; [`OverlayMap::canvas`] maps it to the
    /// SVG's user units.
    pub x: f64,
    pub y: f64,
}

impl ElementOverlay {
    /// The range as rpic object ids, `"sN..sM"` (inclusive).
    pub fn ids(&self) -> String {
        format!(
            "s{}..s{}",
            self.shapes.start,
            self.shapes.end.saturating_sub(1)
        )
    }
}

/// One net's drawn shapes: its wires and dots, and the ground blocks
/// on it (named places draw nothing).
#[derive(Debug, Clone, PartialEq)]
pub struct NetOverlay {
    pub name: String,
    pub shapes: Vec<usize>,
}

/// Map from netlist names back to rpic objects, for result overlays.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct OverlayMap {
    /// Emitted elements, in card order.
    pub elements: Vec<ElementOverlay>,
    /// Named nets, in order of first appearance (`0` first if present).
    pub nets: Vec<NetOverlay>,
    /// The frame that maps pins to the SVG of [`render_svg`].
    pub canvas: CanvasOverlay,
}

/// The result of [`extract`].
#[derive(Debug, Clone, PartialEq)]
pub struct Extraction {
    /// SPICE3 netlist text, ending in `.end`.
    pub netlist: String,
    pub map: OverlayMap,
    pub diagnostics: Vec<PicDiagnostic>,
}

impl Extraction {
    /// True when no diagnostic is an error.
    pub fn is_clean(&self) -> bool {
        self.diagnostics
            .iter()
            .all(|d| d.severity != PicSeverity::Error)
    }
}

/// Compile a figure with the prelude and render it to SVG — the
/// drawing whose shape ids [`OverlayMap`] refers to. Does not require
/// `spice = 1`.
pub fn render_svg(src: &str, opts: &ExtractOptions) -> Result<String, PicError> {
    let c = compile(src, opts)?;
    Ok(rpic_core::to_svg(&c.drawing))
}

/// Extract a SPICE3 netlist from a pic figure.
pub fn extract(src: &str, opts: &ExtractOptions) -> Result<Extraction, PicError> {
    let mut c = compile(src, opts)?;
    let marked = c
        .drawing
        .vars
        .iter()
        .any(|(k, v)| k == "spice" && *v == 1.0);
    if !marked {
        return Err(PicError::NotMarked);
    }
    let snap = if opts.snap.is_finite() && opts.snap > 0.0 {
        opts.snap
    } else {
        DEFAULT_SNAP
    };
    let canvas = canvas_of(&mut c.drawing);
    let mut ex = Extractor::new(src, &c, snap).run();
    ex.map.canvas = canvas;
    Ok(ex)
}

/// The SVG page frame of `d` ([`CanvasOverlay`]), from rpic's SVG
/// transform itself: `svg::place_points` maps places through the very
/// function the emitter draws with, so a probe place at the pic origin
/// gives the translation exactly; the page size follows rpic's
/// `canvas_frame` (content bounds — the union of the shapes' SVG bounds
/// rpic reports per object — or a fixed `canvas`, plus stroke padding
/// and margins).
fn canvas_of(d: &mut Drawing) -> CanvasOverlay {
    let saved = std::mem::take(&mut d.places);
    d.places.push(PlaceInfo {
        label: String::new(),
        at: rpic_core::geom::Point::new(0.0, 0.0),
        block: None,
        span: None,
    });
    let o = rpic_core::svg::place_points(d)[0];
    d.places = saved;
    let (raw_w, raw_h) = match d.canvas {
        Some(b) if !b.is_empty() => (b.width(), b.height()),
        Some(_) => (0.0, 0.0),
        None => {
            // Object bboxes are in SVG units: (x, y, w, h), y down.
            let mut lo = (f64::INFINITY, f64::INFINITY);
            let mut hi = (f64::NEG_INFINITY, f64::NEG_INFINITY);
            for g in rpic_core::svg::object_geometries(d) {
                if let Some((x, y, w, h)) = g.bbox {
                    lo = (lo.0.min(x), lo.1.min(y));
                    hi = (hi.0.max(x + w), hi.1.max(y + h));
                }
            }
            if lo.0.is_finite() {
                ((hi.0 - lo.0) / SVG_PPI, (hi.1 - lo.1) / SVG_PPI)
            } else {
                (0.0, 0.0)
            }
        }
    };
    let pad = d.prelude_thick.max(0.0) / 144.0;
    let m = d.canvas_margin;
    let extent = |v: f64| if v.is_finite() && v > 0.0 { v } else { 0.0 };
    let w = extent(raw_w + 6.0 * pad + m.horizontal());
    let h = extent(raw_h + 6.0 * pad + m.vertical());
    // place_points(0, 0) = (ox · 96, (h − oy) · 96).
    CanvasOverlay {
        w,
        h,
        origin: [o.x / SVG_PPI, h - o.y / SVG_PPI],
        rescale: d.rescale,
    }
}

/// A compiled figure.
struct Compiled {
    drawing: Drawing,
    /// The user's directives in source order: each passthrough entry
    /// with its `+` continuations, one per line.
    directives: Vec<String>,
    /// Lines the prelude occupies ahead of the user source.
    prelude_lines: u32,
    /// The prelude's own element macros (its `define`s not named
    /// `__…`): a call to one of these is an element's own call.
    element_macros: HashSet<String>,
}

fn compile(src: &str, opts: &ExtractOptions) -> Result<Compiled, PicError> {
    let prelude = opts.prelude.unwrap_or(PRELUDE);
    let mut full = String::with_capacity(prelude.len() + src.len() + 1);
    full.push_str(prelude);
    if !prelude.ends_with('\n') {
        full.push('\n');
    }
    let prelude_lines = full.matches('\n').count() as u32;
    full.push_str(src);
    let copts = CompileOptions {
        circuits: true,
        includes: IncludePolicy::Deny,
        ..Default::default()
    };
    let drawing = rpic_core::compile_with_diagnostics(&full, &copts).map_err(|e| {
        let info = &e.info;
        let span = info.line.map(|line| {
            map_span(
                prelude_lines,
                info.file.as_deref(),
                line,
                info.col.unwrap_or(1),
                info.end_col.unwrap_or(info.col.unwrap_or(1)),
            )
        });
        PicError::Compile {
            message: info.message.clone(),
            span,
        }
    })?;
    // Directives: the user's passthrough entries (a prelude has none of
    // its own to contribute). rpic folds the column-1 `+` continuations
    // of a request into its entry, one line per `\n`.
    let directives = drawing
        .passthrough
        .iter()
        .filter(|l| l.span.file.is_none() && l.span.line > prelude_lines)
        .map(|l| directive_text(&l.text))
        .collect();
    let element_macros = prelude
        .lines()
        .filter_map(|l| l.trim_start().strip_prefix("define"))
        .filter(|r| r.starts_with(char::is_whitespace))
        .filter_map(|r| {
            r.split(|c: char| c.is_whitespace() || c == '{')
                .find(|w| !w.is_empty())
        })
        .filter(|n| !n.starts_with("__"))
        .map(str::to_string)
        .collect();
    Ok(Compiled {
        drawing,
        directives,
        prelude_lines,
        element_macros,
    })
}

/// A passthrough entry as a netlist line: the request trimmed at the
/// end, each `+` continuation line trimmed.
fn directive_text(text: &str) -> String {
    let mut lines = text.split('\n');
    let mut out = lines.next().unwrap_or("").trim_end().to_string();
    for cont in lines {
        out.push('\n');
        out.push_str(cont.trim());
    }
    out
}

/// Map a position in the prelude+user stream back to its source.
fn map_span(prelude_lines: u32, file: Option<&str>, line: u32, col: u32, end_col: u32) -> PicSpan {
    match file {
        Some(f) => PicSpan {
            file: Some(f.to_string()),
            line,
            col,
            end_col,
        },
        None if line > prelude_lines => PicSpan {
            file: None,
            line: line - prelude_lines,
            col,
            end_col,
        },
        None => PicSpan {
            file: Some("spice.pic".into()),
            line,
            col,
            end_col,
        },
    }
}

/// Pins of each supported card letter (D-0019 + `T`/`O` + D-0026), in
/// card order. A `Q` may also carry the substrate ([`BJT4_PINS`]); a
/// `K` has none.
fn pins_for(letter: char) -> Option<&'static [&'static str]> {
    Some(match letter {
        'R' | 'C' | 'L' | 'V' | 'I' | 'D' | 'W' | 'F' | 'H' => &["P", "N"],
        'S' | 'E' | 'G' => &["P", "N", "Cp", "Cn"],
        'K' => &[],
        'Q' => &["C", "B", "E"],
        'M' => &["D", "G", "S", "B"],
        'J' | 'Z' => &["D", "G", "S"],
        'X' => &["Inp", "Inm", "Out"],
        'T' | 'O' => &["P1", "N1", "P2", "N2"],
        _ => return None,
    })
}

#[derive(Clone, Copy, PartialEq)]
enum BlockKind {
    Plain,
    Element,
    Ground,
}

/// What a terminal is.
#[derive(Clone, Copy)]
enum Term {
    /// Pin `pin` (index into the element's pin list) of element `elem`.
    Pin {
        elem: usize,
        pin: usize,
    },
    Ground,
    /// A named place (index into the extractor's place list).
    Place(usize),
    /// A vertex of a wire.
    Wire,
    Dot,
}

struct Terminal {
    at: Pt,
    /// The shape the terminal belongs to; [`NO_SHAPE`] for places,
    /// which draw nothing (so they never decide net order).
    shape: usize,
    term: Term,
}

struct Element {
    refdes: String,
    pins: &'static [&'static str],
    /// Terminal index of each pin, in card order.
    terms: Vec<usize>,
    value: String,
    /// The call argument `value` was read from, when it was.
    value_arg: Option<usize>,
    block: usize,
    /// The element's call site in the user source.
    span: Option<PicSpan>,
}

/// [`Terminal::shape`] of a named place.
const NO_SHAPE: usize = usize::MAX;

/// A named place that takes part in net naming.
struct Place {
    label: String,
    span: Option<PicSpan>,
}

struct Extractor<'a> {
    src: &'a str,
    d: &'a Drawing,
    directives: &'a [String],
    prelude_lines: u32,
    element_macros: &'a HashSet<String>,
    snap: f64,
    diags: Vec<PicDiagnostic>,
    places: Vec<Place>,
}

impl<'a> Extractor<'a> {
    fn new(src: &'a str, c: &'a Compiled, snap: f64) -> Self {
        Self {
            src,
            d: &c.drawing,
            directives: &c.directives,
            prelude_lines: c.prelude_lines,
            element_macros: &c.element_macros,
            snap,
            diags: Vec::new(),
            places: Vec::new(),
        }
    }

    fn diag(
        &mut self,
        severity: PicSeverity,
        kind: PicDiagKind,
        message: String,
        span: Option<PicSpan>,
    ) {
        self.diags.push(PicDiagnostic {
            severity,
            kind,
            message,
            span,
        });
    }

    fn span(&self, s: &rpic_core::Span) -> PicSpan {
        map_span(
            self.prelude_lines,
            s.file.as_deref(),
            s.line,
            s.col,
            s.end_col,
        )
    }

    fn shape_span(&self, i: usize) -> Option<PicSpan> {
        let s = self.d.shape_spans.get(i)?.as_ref()?;
        Some(self.span(s))
    }

    /// The label and center of shape `i` if it is a labeled marker
    /// (`circle invis rad 0`).
    fn marker(&self, i: usize) -> Option<(&'a str, Pt)> {
        let d = self.d;
        let label = d.shape_labels.get(i)?.as_deref()?;
        match &d.shapes[i] {
            Shape::Circle {
                c, r, dot, style, ..
            } if *r == 0.0 && !*dot && style.invis => Some((label, (c.x, c.y))),
            _ => None,
        }
    }

    /// Direct-child markers of block `b`.
    fn markers_of(&self, b: usize) -> Vec<(usize, &'a str, Pt)> {
        let (lo, hi) = self.d.blocks[b].shapes;
        (lo..hi.min(self.d.shapes.len()))
            .filter(|&i| self.d.shape_blocks.get(i).copied().flatten() == Some(b))
            .filter_map(|i| self.marker(i).map(|(l, p)| (i, l, p)))
            .collect()
    }

    fn run(mut self) -> Extraction {
        let d = self.d;
        if self.src.lines().any(|l| {
            let t = l.trim();
            t.starts_with("copy") && t.contains("\"circuits\"")
        }) {
            self.diag(
                PicSeverity::Warning,
                PicDiagKind::Prelude,
                "`copy \"circuits\"` reloads rpic's std library over the dune prelude, \
                 turning elements back into plain drawings; dune-pic loads the library itself"
                    .into(),
                None,
            );
        }

        // 1. Classify blocks.
        let kinds: Vec<BlockKind> = (0..d.blocks.len())
            .map(|b| {
                let ms = self.markers_of(b);
                if ms.iter().any(|m| m.1 == GROUND_MARKER) {
                    BlockKind::Ground
                } else if ms.iter().any(|m| ELEMENT_MARKERS.contains(&m.1)) {
                    BlockKind::Element
                } else {
                    BlockKind::Plain
                }
            })
            .collect();
        // Inside a special block (at any depth)?
        let in_special = |mut b: Option<usize>| {
            while let Some(bi) = b {
                if kinds[bi] != BlockKind::Plain {
                    return true;
                }
                b = d.blocks[bi].parent;
            }
            false
        };
        // A shape is internal when any enclosing block is special.
        let internal = |i: usize| in_special(d.shape_blocks.get(i).copied().flatten());

        let mut terms: Vec<Terminal> = Vec::new();
        let mut elements: Vec<Element> = Vec::new();

        // 2. Elements and grounds, in source order.
        let mut order: Vec<usize> = (0..d.blocks.len()).collect();
        order.sort_by_key(|&b| d.blocks[b].shapes.0);
        let mut seen: HashMap<String, String> = HashMap::new();
        for &b in &order {
            let ms = self.markers_of(b);
            match kinds[b] {
                BlockKind::Plain => {}
                BlockKind::Ground => {
                    for &(i, l, p) in &ms {
                        if l == GROUND_MARKER {
                            terms.push(Terminal {
                                at: p,
                                shape: i,
                                term: Term::Ground,
                            });
                        }
                    }
                }
                BlockKind::Element => {
                    if let Some(e) = self.element(b, &ms, &mut terms, &mut seen, elements.len()) {
                        elements.push(e);
                    }
                }
            }
        }

        self.check_references(&elements);

        // Named places (D-0004 §3): the user's `Label: position`
        // statements, not those of the prelude, the std library or the
        // inside of an element.
        for p in &d.places {
            let span = p.span.as_ref().map(|s| self.span(s));
            if span.as_ref().is_some_and(|s| s.file.is_some()) || in_special(p.block) {
                continue;
            }
            if let Some(refdes) = seen.get(&p.label.to_ascii_lowercase()) {
                self.diag(
                    PicSeverity::Warning,
                    PicDiagKind::NodeNameConflict,
                    format!(
                        "place `{}` has the name of element `{refdes}`; it names no net",
                        p.label
                    ),
                    span,
                );
                continue;
            }
            terms.push(Terminal {
                at: (p.at.x, p.at.y),
                shape: NO_SHAPE,
                term: Term::Place(self.places.len()),
            });
            self.places.push(Place {
                label: p.label.clone(),
                span,
            });
        }

        // 3. Wires and dots.
        let mut segments: Vec<(Pt, Pt, usize)> = Vec::new();
        for (i, s) in d.shapes.iter().enumerate() {
            if internal(i) {
                continue;
            }
            match s {
                Shape::Path { pts, style, .. } if !style.invis && !pts.is_empty() => {
                    let first = terms.len();
                    for p in pts {
                        terms.push(Terminal {
                            at: (p.x, p.y),
                            shape: i,
                            term: Term::Wire,
                        });
                    }
                    for w in pts.windows(2) {
                        segments.push(((w[0].x, w[0].y), (w[1].x, w[1].y), first));
                    }
                }
                Shape::Circle { c, dot: true, .. } => terms.push(Terminal {
                    at: (c.x, c.y),
                    shape: i,
                    term: Term::Dot,
                }),
                _ => {}
            }
        }

        // 4. Union-find.
        let mut uf = UnionFind::new(terms.len());
        for w in terms.windows(2).enumerate() {
            let (k, pair) = w;
            if let (Term::Wire, Term::Wire) = (pair[0].term, pair[1].term)
                && pair[0].shape == pair[1].shape
            {
                uf.union(k, k + 1);
            }
        }
        let points: Vec<Pt> = terms.iter().map(|t| t.at).collect();
        join_geometry(&mut uf, &points, &segments, self.snap);
        // Nets that share a place name are one node (net labels
        // connect).
        let mut by_name: HashMap<String, usize> = HashMap::new();
        for (k, t) in terms.iter().enumerate() {
            if let Term::Place(n) = t.term {
                let key = self.places[n].label.to_ascii_lowercase();
                match by_name.get(&key) {
                    Some(&other) => uf.union(k, other),
                    None => {
                        by_name.insert(key, k);
                    }
                }
            }
        }

        // 5. Gather nets.
        let roots: Vec<usize> = (0..terms.len()).map(|k| uf.find(k)).collect();
        let mut nets: BTreeMap<usize, Vec<usize>> = BTreeMap::new(); // root -> terms
        for (k, &r) in roots.iter().enumerate() {
            nets.entry(r).or_default().push(k);
        }

        // 6. Name nets.
        let user_names: Vec<String> = self
            .places
            .iter()
            .map(|p| p.label.to_ascii_lowercase())
            .collect();
        let mut name_of: HashMap<usize, String> = HashMap::new();
        // Nets in order of first appearance.
        let mut net_order: Vec<(usize, usize)> = nets
            .iter()
            .map(|(&r, ks)| (ks.iter().map(|&k| terms[k].shape).min().unwrap_or(0), r))
            .collect();
        net_order.sort();
        for &(_, r) in &net_order {
            let ks = &nets[&r];
            let grounded = ks.iter().any(|&k| matches!(terms[k].term, Term::Ground));
            // Place names in definition order.
            let mut names: Vec<usize> = ks
                .iter()
                .filter_map(|&k| match terms[k].term {
                    Term::Place(n) => Some(n),
                    _ => None,
                })
                .collect();
            names.sort_unstable();
            let mut distinct: Vec<String> = Vec::new();
            for n in names {
                let l = &self.places[n].label;
                if !distinct.iter().any(|m| m.eq_ignore_ascii_case(l)) {
                    distinct.push(l.clone());
                }
            }
            if grounded {
                if let Some(n) = distinct.first() {
                    let span = self.label_span(n);
                    self.diag(
                        PicSeverity::Warning,
                        PicDiagKind::NodeNameConflict,
                        format!("place `{n}` is on the ground net; it is named `0`"),
                        span,
                    );
                }
                name_of.insert(r, "0".into());
            } else if let Some(first) = distinct.first() {
                if distinct.len() > 1 {
                    let span = self.label_span(&distinct[1]);
                    self.diag(
                        PicSeverity::Warning,
                        PicDiagKind::NodeNameConflict,
                        format!(
                            "one net named {}; using `{first}`",
                            distinct
                                .iter()
                                .map(|n| format!("`{n}`"))
                                .collect::<Vec<_>>()
                                .join(", ")
                        ),
                        span,
                    );
                }
                name_of.insert(r, first.clone());
            }
        }
        let mut auto = 0usize;
        for &(_, r) in &net_order {
            if name_of.contains_key(&r) {
                continue;
            }
            let has_pin = nets[&r]
                .iter()
                .any(|&k| matches!(terms[k].term, Term::Pin { .. }));
            if !has_pin {
                continue;
            }
            let name = loop {
                auto += 1;
                let n = format!("n{auto}");
                if !user_names.contains(&n) {
                    break n;
                }
            };
            name_of.insert(r, name);
        }

        // 7. Electrical checks.
        for &(_, r) in &net_order {
            let ks = &nets[&r];
            let pins: Vec<usize> = ks
                .iter()
                .copied()
                .filter(|&k| matches!(terms[k].term, Term::Pin { .. }))
                .collect();
            let grounded = ks.iter().any(|&k| matches!(terms[k].term, Term::Ground));
            if pins.is_empty() {
                let drawn = ks
                    .iter()
                    .copied()
                    .find(|&k| matches!(terms[k].term, Term::Wire | Term::Dot));
                if let Some(k) = drawn {
                    let what = match name_of.get(&r) {
                        Some(n) => format!("net `{n}`"),
                        None => "wire".into(),
                    };
                    let span = self.shape_span(terms[k].shape).filter(|s| s.file.is_none());
                    self.diag(
                        PicSeverity::Warning,
                        PicDiagKind::FloatingNet,
                        format!("{what} connects to no element pin"),
                        span,
                    );
                } else if let Some(n) = ks.iter().find_map(|&k| match terms[k].term {
                    Term::Place(n) => Some(n),
                    _ => None,
                }) {
                    // Only places: a label on empty space.
                    let p = &self.places[n];
                    let msg = format!("place `{}` names no net: no wire or pin is there", p.label);
                    let span = p.span.clone();
                    self.diag(PicSeverity::Warning, PicDiagKind::FloatingNet, msg, span);
                }
                continue;
            }
            if pins.len() == 1 && !grounded {
                let Term::Pin { elem, pin } = terms[pins[0]].term else {
                    unreachable!()
                };
                let e = &elements[elem];
                let span = e.span.clone();
                let net = name_of.get(&r).cloned().unwrap_or_default();
                let msg = format!(
                    "pin {}.{} is dangling: net `{net}` reaches no other element pin",
                    e.refdes, e.pins[pin]
                );
                self.diag(PicSeverity::Warning, PicDiagKind::DanglingPin, msg, span);
            }
        }

        // A Q card's 4th name is the substrate only when it is not a
        // model name (INP2Q looks it up in the model table).
        for e in &elements {
            if e.pins.len() == 4 && e.refdes.to_ascii_uppercase().starts_with('Q') {
                let sub = &name_of[&roots[e.terms[3]]];
                let model = e.value.split_whitespace().next().unwrap_or("");
                if sub.eq_ignore_ascii_case(model) {
                    let msg = format!(
                        "`{}`: substrate net `{sub}` has the name of the model; \
                         SPICE would read it as the model and the next word as the model name",
                        e.refdes
                    );
                    let span = e.span.clone();
                    self.diag(
                        PicSeverity::Warning,
                        PicDiagKind::NodeNameConflict,
                        msg,
                        span,
                    );
                }
            }
        }

        // 8. Emit.
        let mut netlist = String::from("* netlist extracted by dune-pic\n");
        let mut map = OverlayMap::default();
        for e in &elements {
            netlist.push_str(&e.refdes);
            for &k in &e.terms {
                netlist.push(' ');
                netlist.push_str(&name_of[&roots[k]]);
            }
            if !e.value.is_empty() {
                netlist.push(' ');
                netlist.push_str(&e.value);
            }
            netlist.push('\n');
            let (lo, hi) = d.blocks[e.block].shapes;
            let pins = e
                .pins
                .iter()
                .zip(&e.terms)
                .map(|(&name, &k)| PinOverlay {
                    name: name.to_string(),
                    net: name_of[&roots[k]].clone(),
                    x: terms[k].at.0,
                    y: terms[k].at.1,
                })
                .collect();
            let letter = e.refdes.chars().next().unwrap_or(' ').to_ascii_uppercase();
            let (value, params) = match e
                .value_arg
                .and_then(|k| self.value_span(e.block, k, letter))
            {
                Some((v, p)) => (Some(v), p),
                None => (None, Vec::new()),
            };
            map.elements.push(ElementOverlay {
                refdes: e.refdes.clone(),
                shapes: lo..hi,
                pins,
                value,
                params,
                principal: spans::principal(letter).map(str::to_string),
            });
        }
        for dir in self.directives {
            if dir.eq_ignore_ascii_case(".end") {
                continue;
            }
            netlist.push_str(dir);
            netlist.push('\n');
        }
        netlist.push_str(".end\n");

        // Overlay of nets: wires, dots and ground blocks.
        let mut net_shapes: BTreeMap<usize, Vec<usize>> = BTreeMap::new();
        for (k, t) in terms.iter().enumerate() {
            match t.term {
                Term::Wire | Term::Dot => net_shapes.entry(roots[k]).or_default().push(t.shape),
                Term::Ground => {
                    let b = d.shape_blocks[t.shape].expect("marker inside its block");
                    let (lo, hi) = d.blocks[b].shapes;
                    net_shapes.entry(roots[k]).or_default().extend(lo..hi);
                }
                Term::Pin { .. } | Term::Place(_) => {}
            }
        }
        let mut emitted: Vec<String> = Vec::new();
        let mut ordered: Vec<(usize, usize)> = net_order.clone();
        ordered.sort_by_key(|&(first, r)| (name_of.get(&r).map(|n| n != "0"), first));
        for (_, r) in ordered {
            let Some(name) = name_of.get(&r) else {
                continue;
            };
            let mut shapes = net_shapes.remove(&r).unwrap_or_default();
            shapes.sort_unstable();
            shapes.dedup();
            // Nets merged by name share one entry.
            if let Some(pos) = emitted.iter().position(|n| n == name) {
                map.nets[pos].shapes.extend(shapes);
                map.nets[pos].shapes.sort_unstable();
                map.nets[pos].shapes.dedup();
                continue;
            }
            emitted.push(name.clone());
            map.nets.push(NetOverlay {
                name: name.clone(),
                shapes,
            });
        }

        Extraction {
            netlist,
            map,
            diagnostics: self.diags,
        }
    }

    /// Validate an element block and register its pin terminals.
    fn element(
        &mut self,
        b: usize,
        ms: &[(usize, &'a str, Pt)],
        terms: &mut Vec<Terminal>,
        seen: &mut HashMap<String, String>,
        index: usize,
    ) -> Option<Element> {
        let d = self.d;
        let Some(refdes) = d.blocks[b].label.clone() else {
            let value = self.value(b, ms, ' ').map(|v| v.0).unwrap_or_default();
            let at = ms.first().map(|m| m.2).unwrap_or((0.0, 0.0));
            let msg = format!(
                "element without a label (refdes) at ({:.3}, {:.3}){}; skipped — write `R1: resistor(…)`",
                at.0,
                at.1,
                if value.is_empty() {
                    String::new()
                } else {
                    format!(", value `{value}`")
                }
            );
            let span = self.block_span(b);
            self.diag(PicSeverity::Error, PicDiagKind::UnlabeledElement, msg, span);
            return None;
        };
        let span = self.block_span(b);
        let letter = refdes.chars().next().unwrap_or(' ').to_ascii_uppercase();
        let Some(mut pins) = pins_for(letter) else {
            self.diag(
                PicSeverity::Error,
                PicDiagKind::UnknownElement,
                format!(
                    "`{refdes}`: element letter `{letter}` is not supported ({LETTERS}); skipped"
                ),
                span,
            );
            return None;
        };
        if letter == 'Q' && ms.iter().any(|m| m.1 == "S") {
            pins = BJT4_PINS;
        }
        if letter == 'X' {
            let n = subckt_arity(ms);
            if n > 0 {
                pins = &SUBCKT_PINS[..n];
            }
        }
        if letter == 'K' && !ms.iter().any(|m| m.1 == COUPLING_MARKER) {
            self.diag(
                PicSeverity::Error,
                PicDiagKind::MissingPin,
                format!(
                    "`{refdes}`: a `K` element is drawn with `coupling(L1, L2, k)`, \
                     not this macro; skipped"
                ),
                span,
            );
            return None;
        }
        let value = self.value(b, ms, letter);
        let key = refdes.to_ascii_lowercase();
        if let Some(prev) = seen.get(&key) {
            self.diag(
                PicSeverity::Error,
                PicDiagKind::DuplicateRefdes,
                format!("refdes `{refdes}` already used by `{prev}`; skipped"),
                span,
            );
            return None;
        }
        let mut pin_terms = Vec::with_capacity(pins.len());
        let mut missing = Vec::new();
        for (pi, &pin) in pins.iter().enumerate() {
            match ms.iter().find(|m| m.1 == pin) {
                Some(&(i, _, p)) => {
                    pin_terms.push(terms.len());
                    terms.push(Terminal {
                        at: p,
                        shape: i,
                        term: Term::Pin {
                            elem: index,
                            pin: pi,
                        },
                    });
                }
                None => missing.push(pin),
            }
        }
        if !missing.is_empty() {
            // Undo the pins registered for this element.
            terms.truncate(terms.len() - pin_terms.len());
            self.diag(
                PicSeverity::Error,
                PicDiagKind::MissingPin,
                format!(
                    "`{refdes}`: a `{letter}` element needs pins {}, but the drawn element \
                     lacks {} (wrong refdes letter for this macro?); skipped",
                    pins.join(", "),
                    missing.join(", ")
                ),
                span,
            );
            return None;
        }
        seen.insert(key, refdes.clone());
        let Some((value, value_arg)) = value else {
            self.diag(
                PicSeverity::Error,
                PicDiagKind::MissingValue,
                format!(
                    "`{refdes}` draws a display text instead of its value, but its call \
                     is not the element's own macro (a wrapper?), so the value cannot \
                     be read; the card is incomplete"
                ),
                span.clone(),
            );
            return Some(Element {
                refdes,
                pins,
                terms: pin_terms,
                value: String::new(),
                value_arg: None,
                block: b,
                span,
            });
        };
        if value.is_empty() {
            // A source without a value is 0 V / 0 A in SPICE; anything
            // else is incomplete.
            let (sev, what) = if matches!(letter, 'V' | 'I') {
                (PicSeverity::Warning, "it is a 0 V/0 A source")
            } else {
                (PicSeverity::Error, "the card is incomplete")
            };
            self.diag(
                sev,
                PicDiagKind::MissingValue,
                format!("`{refdes}` has no value/model text; {what}"),
                span.clone(),
            );
        }
        Some(Element {
            refdes,
            pins,
            terms: pin_terms,
            value,
            value_arg,
            block: b,
            span,
        })
    }

    /// Elements whose value names other elements: an `F`/`H` must
    /// start with the refdes of a `V` source (the controlling branch), a
    /// `K` with the refdes of two `L` elements. A card without them is
    /// invalid, so these are errors (reported as [`PicDiagKind::MissingValue`]:
    /// the value lacks what the card needs). An empty value was already
    /// reported.
    fn check_references(&mut self, elements: &[Element]) {
        let letter_of = |name: &str| {
            elements
                .iter()
                .find(|e| e.refdes.eq_ignore_ascii_case(name))
                .and_then(|e| e.refdes.chars().next())
                .map(|c| c.to_ascii_uppercase())
        };
        for e in elements {
            let letter = e.refdes.chars().next().unwrap_or(' ').to_ascii_uppercase();
            let toks: Vec<&str> = e.value.split_whitespace().collect();
            if toks.is_empty() {
                continue;
            }
            let (want, refs, what): (char, &[&str], &str) = match letter {
                'F' | 'H' => (
                    'V',
                    &toks[..1],
                    "a controlling voltage source (`Vname gain`)",
                ),
                'K' => (
                    'L',
                    &toks[..toks.len().min(2)],
                    "two inductors (`L1, L2, k`)",
                ),
                _ => continue,
            };
            for r in refs {
                let problem = match letter_of(r) {
                    Some(l) if l == want => continue,
                    Some(_) => format!("`{r}` is not a `{want}` element"),
                    None if r
                        .chars()
                        .next()
                        .is_some_and(|c| c.eq_ignore_ascii_case(&want)) =>
                    {
                        format!("no element `{r}` in the figure")
                    }
                    None => format!("`{r}` is not a `{want}` refdes"),
                };
                self.diag(
                    PicSeverity::Error,
                    PicDiagKind::MissingValue,
                    format!(
                        "`{}` needs {what}: {problem}; the card is invalid",
                        e.refdes
                    ),
                    e.span.clone(),
                );
            }
            if letter == 'K' && toks.len() < 3 {
                self.diag(
                    PicSeverity::Error,
                    PicDiagKind::MissingValue,
                    format!("`{}` has no coupling coefficient", e.refdes),
                    e.span.clone(),
                );
            }
        }
    }

    /// Where block `b` was asked for: its outermost macro call (or its
    /// inline `[`) — in the user's source for every element the figure
    /// writes, even though its shapes point into the prelude.
    fn block_span(&self, b: usize) -> Option<PicSpan> {
        self.d.blocks[b].span.as_ref().map(|s| self.span(s))
    }

    /// The value/model of element block `b` (D-0004 §2): the macro
    /// argument after the pin positions — index 1 for elements centered
    /// on an `At` anchor, 4 for the four-point `E`/`G`, N for a generic
    /// `X` of N pins, 2 otherwise —
    /// verbatim from the user's source. A `K` (`coupling(L1, L2, k)`)
    /// takes all three arguments, `L1 L2 k`; its drawing shows only
    /// `k=…`, so it has no drawn fallback.
    ///
    /// A call to one of the [`DISPLAY_MACROS`] with one more argument,
    /// non-empty, carries a display text that the prelude draws instead
    /// of the value: the value still comes from its own argument, and
    /// the check below compares the drawing with the display. A
    /// mismatch then falls back on the drawn text, which is the display
    /// — wrong, but it only happens when the call is not the element's
    /// (and the extraction would be wrong without the display too).
    /// A drawing that shows a display (`Disp` marker) without such a
    /// call — a wrapper macro passing one — has no trustworthy value:
    /// `None`.
    ///
    /// The call is trusted only when its argument is what the prelude
    /// drew (both normalized by pic), which rules out a user wrapper
    /// macro whose arguments are not the element's (`BlockInfo.call` is
    /// the *outermost* call). Fallbacks, in order: rpic's normalized
    /// argument (an argument itself split over lines, see
    /// [`Self::raw_arg`]); the drawn text (no call — an inline block —
    /// or a mismatch).
    ///
    /// With the value, the index of the call argument it was read from
    /// (`None` for a fallback and for a `K`), for
    /// [`ElementOverlay::value`].
    fn value(
        &self,
        b: usize,
        ms: &[(usize, &'a str, Pt)],
        letter: char,
    ) -> Option<(String, Option<usize>)> {
        let coupling = letter == 'K';
        let drawn = self.value_text(b);
        // A drawn display is not the value: nothing to fall back on.
        let shows_display = ms.iter().any(|m| m.1 == DISPLAY_MARKER);
        let fallback = if shows_display {
            None
        } else if coupling {
            Some((String::new(), None))
        } else {
            Some((drawn.clone(), None))
        };
        let arity = if letter == 'X' { subckt_arity(ms) } else { 0 };
        let k = match letter {
            'E' | 'G' => 4,
            _ if ms.iter().any(|m| m.1 == ANCHOR_MARKER) => 1,
            // A generic subcircuit: the name follows its N points.
            'X' if arity > 0 => arity,
            _ => 2,
        };
        let Some(call) = &self.d.blocks[b].call else {
            return fallback;
        };
        let Some(arg) = call.args.get(k) else {
            return fallback;
        };
        if coupling && call.args.len() != 3 {
            return fallback;
        }
        let words = |s: &str| s.split_whitespace().collect::<Vec<_>>().join(" ");
        let spliced = unquote(arg);
        // A display text (one argument past the value, non-empty) is
        // what the prelude drew, so it is what the call must match.
        // Only a call to the prelude macro itself has one: a wrapper's
        // extra argument says nothing about the element.
        let display = (DISPLAY_MACROS.contains(&call.name.as_str()) && call.args.len() == k + 2)
            .then(|| words(unquote(&call.args[k + 1])))
            .filter(|d| !d.is_empty());
        if shows_display && display.is_none() {
            // The display came through a wrapper: its arguments are
            // not the element's.
            return None;
        }
        let expect = if coupling {
            format!("k={}", words(spliced))
        } else if let Some(d) = display {
            d
        } else {
            words(spliced)
        };
        if !drawn.is_empty() && expect != words(&drawn) {
            return fallback;
        }
        let pick = |i: usize| unquote(&self.raw_arg(call, i)).trim().to_string();
        Some(if coupling {
            ((0..3).map(pick).collect::<Vec<_>>().join(" "), None)
        } else {
            (pick(k), Some(k))
        })
    }

    /// Argument `i` of `call` as the user wrote it (`MacroCall.raw_args`:
    /// `1e-9` stays `1e-9`) when it is one line of the user's source;
    /// otherwise — an argument split by `\` continuations, or one that
    /// is not the user's text — rpic's normalized argument.
    fn raw_arg(&self, call: &MacroCall, i: usize) -> String {
        match call.raw_args.get(i) {
            Some(raw)
                if call.raw_args.len() == call.args.len()
                    && raw.span.file.is_none()
                    && raw.span.line > self.prelude_lines
                    && raw.end_line == raw.span.line =>
            {
                raw.text.clone()
            }
            _ => call.args[i].clone(),
        }
    }

    /// [`ElementOverlay::value`] and [`ElementOverlay::params`] of the
    /// element of block `b` whose value is argument `k` of its call:
    /// only for a call to one of the prelude's element macros whose
    /// raw argument is in the user's source.
    fn value_span(
        &self,
        b: usize,
        k: usize,
        letter: char,
    ) -> Option<(ValueSpanOverlay, Vec<ParamSpanOverlay>)> {
        let call = self.d.blocks[b].call.as_ref()?;
        if !self.element_macros.contains(&call.name) || call.raw_args.len() != call.args.len() {
            return None;
        }
        let raw = call.raw_args.get(k)?;
        if raw.span.file.is_some() || raw.span.line <= self.prelude_lines {
            return None;
        }
        let chars: Vec<char> = raw.text.chars().collect();
        let pos = spans::positions(&chars, raw.span.line - self.prelude_lines, raw.span.col);
        // The layout must land where rpic says the argument ends;
        // anything else (a source convention this walk does not
        // share) gives no span rather than a wrong one.
        if pos[chars.len()] != (raw.end_line - self.prelude_lines, raw.span.end_col) {
            return None;
        }
        let (a, z) = spans::value_range(&chars);
        let value = ValueSpanOverlay {
            span: spans::range(&pos, a, z),
            text: chars[a..z].iter().collect(),
        };
        Some((value, spans::param_overlays(letter, &chars, a, z, &pos)))
    }

    /// The first text shape inside block `b` (any depth), lines joined
    /// by spaces, trimmed.
    fn value_text(&self, b: usize) -> String {
        let (lo, hi) = self.d.blocks[b].shapes;
        for i in lo..hi.min(self.d.shapes.len()) {
            if let Shape::Text { text, .. } = &self.d.shapes[i] {
                let joined: Vec<&str> = text.iter().map(|t| t.s.trim()).collect();
                return joined.join(" ").trim().to_string();
            }
        }
        String::new()
    }

    /// Where the first place named `label` is defined.
    fn label_span(&self, label: &str) -> Option<PicSpan> {
        self.places
            .iter()
            .find(|p| p.label.eq_ignore_ascii_case(label))
            .and_then(|p| p.span.clone())
    }
}

/// The number of pins of a generic subcircuit block (`P1` … `PN`, the
/// markers of `subckt2` … `subckt7`): how many of [`SUBCKT_PINS`] it
/// carries in a row from `P1`; 0 for any other `X` (the op-amp's
/// `Inp`/`Inm`/`Out`).
fn subckt_arity(ms: &[(usize, &str, Pt)]) -> usize {
    SUBCKT_PINS
        .iter()
        .take_while(|p| ms.iter().any(|m| m.1 == **p))
        .count()
}

/// A lone string argument splices as its content (pic's
/// quote-at-use-site idiom), so `"DX"` is the value `DX`.
fn unquote(arg: &str) -> &str {
    let t = arg.trim();
    match t.strip_prefix('"').and_then(|r| r.strip_suffix('"')) {
        Some(inner) if !inner.contains('"') => inner,
        _ => arg,
    }
}