dune-netlist 0.6.1

SPICE3f5 netlist lexer, parser, and IR
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
//! Control (dot) card parsing: analyses, `.options`, `.ic`/`.nodeset`
//! and the output cards. Dispatch is by exact keyword like
//! `INP2dot`'s `strcmp` chain (`corpus/spice3f5/src/lib/inp/inp2dot.c`);
//! `.print`/`.plot`/`.save`/`.four` are parsed here into the IR even
//! though the 3f5 handles them in the front end (`fte/dotcards.c`).

use crate::deck::Card;
use crate::diag::Diagnostic;
use crate::ir::{
    AcSuffix, Analysis, DcSweep, Netlist, NodeInit, NodeInitKind, OutVar, Output, OutputKind,
    Param, ParamValue, PzInput, PzWhich, Variation,
};
use crate::param::ParamEnv;
use crate::scan::Scanner;
use crate::span::Span;

/// `.options` keywords whose value is a word, not a number.
const STRING_OPTIONS: &[&str] = &["method", "compat"];

pub(crate) struct DotCtx<'a> {
    pub card: &'a Card,
    pub diags: &'a mut Vec<Diagnostic>,
    pub env: &'a ParamEnv,
}

impl DotCtx<'_> {
    fn err(&mut self, span: Span, msg: impl Into<String>) {
        self.diags.push(Diagnostic::error(msg.into(), span));
    }

    fn warn(&mut self, span: Span, msg: impl Into<String>) {
        self.diags.push(Diagnostic::warning(msg.into(), span));
    }

    fn value_opt(&mut self, sc: &mut Scanner) -> Option<f64> {
        if let Some((v, _)) = sc.try_value() {
            return Some(v);
        }
        let tok = sc.peek_tok()?;
        if !tok.text.starts_with('{') {
            return None;
        }
        let span = sc.span(&tok);
        let text = tok.lc();
        sc.next_tok();
        match self.env.eval_brace(&text) {
            Ok(v) => Some(v),
            Err(e) => {
                self.err(span, e);
                Some(0.0)
            }
        }
    }

    fn value_req(&mut self, sc: &mut Scanner, what: &str) -> Option<f64> {
        match self.value_opt(sc) {
            Some(v) => Some(v),
            None => {
                let span = sc
                    .peek_tok()
                    .map(|t| sc.span(&t))
                    .unwrap_or_else(|| sc.here());
                self.err(span, format!("missing {what}"));
                None
            }
        }
    }
}

/// Parse one non-structural dot card into `nl`. Returns `false` when
/// the keyword is not recognized here.
pub(crate) fn parse_dot(
    keyword: &str,
    card: &Card,
    diags: &mut Vec<Diagnostic>,
    env: &ParamEnv,
    nl: &mut Netlist,
) -> bool {
    let mut ctx = DotCtx { card, diags, env };
    let span = card.span();
    match keyword {
        ".op" => nl.analyses.push(Analysis::Op { span }),
        ".dc" => dot_dc(&mut ctx, nl, span),
        ".ac" => dot_ac(&mut ctx, nl, span),
        ".tran" => dot_tran(&mut ctx, nl, span),
        ".pz" => dot_pz(&mut ctx, nl, span),
        ".noise" => dot_noise(&mut ctx, nl, span),
        ".disto" => dot_disto(&mut ctx, nl, span),
        ".sens" => dot_sens(&mut ctx, nl, span),
        ".tf" => dot_tf(&mut ctx, nl, span),
        ".sp" => dot_sp(&mut ctx, nl, span),
        ".pss" => dot_pss(&mut ctx, nl, span),
        ".options" | ".option" | ".opt" => dot_options(&mut ctx, nl),
        ".ic" => dot_nodeinit(&mut ctx, nl, NodeInitKind::Ic),
        ".nodeset" => dot_nodeinit(&mut ctx, nl, NodeInitKind::Nodeset),
        ".print" => dot_print_plot(&mut ctx, nl, span, OutputKind::Print),
        ".plot" => dot_print_plot(&mut ctx, nl, span, OutputKind::Plot),
        ".save" => dot_save(&mut ctx, nl, span),
        ".four" | ".fourier" => dot_four(&mut ctx, nl, span),
        ".width" => dot_width(&mut ctx, nl, span),
        ".measure" | ".meas" => {
            let card = ctx.card;
            if let Some(m) = crate::meas::parse_measure_card(
                &card.text,
                span,
                &|s, e| card.span_of(s, e),
                ctx.diags,
            ) {
                nl.measures.push(m);
            }
        }
        ".temp" => ctx.warn(span, ".temp card obsolete - use .options temp and tnom"),
        ".lib" => ctx.err(span, ".lib is not supported yet (use .include)"),
        _ => return false,
    }
    true
}

fn variation(tok: &str) -> Option<Variation> {
    match tok {
        "dec" => Some(Variation::Dec),
        "oct" => Some(Variation::Oct),
        "lin" => Some(Variation::Lin),
        _ => None,
    }
}

/// `.dc SRCNAM VSTART VSTOP VINCR [SRC2 START2 STOP2 INCR2]`
fn dot_dc(ctx: &mut DotCtx, nl: &mut Netlist, span: Span) {
    let mut sc = Scanner::new(ctx.card);
    sc.next_tok(); // `.dc`
    let mut sweeps = Vec::new();
    while let Some(tok) = sc.next_tok() {
        let src = tok.lc();
        let (Some(start), Some(stop), Some(step)) = (
            ctx.value_req(&mut sc, "sweep start"),
            ctx.value_req(&mut sc, "sweep stop"),
            ctx.value_req(&mut sc, "sweep increment"),
        ) else {
            return;
        };
        sweeps.push(DcSweep {
            src,
            start,
            stop,
            step,
        });
        if sweeps.len() > 2 {
            let s = sc.here();
            ctx.err(s, ".dc takes at most two sweep sources");
            return;
        }
    }
    if sweeps.is_empty() {
        ctx.err(span, ".dc needs a source and sweep values");
        return;
    }
    nl.analyses.push(Analysis::Dc { sweeps, span });
}

/// `.ac DEC|OCT|LIN N FSTART FSTOP`
fn dot_ac(ctx: &mut DotCtx, nl: &mut Netlist, span: Span) {
    let mut sc = Scanner::new(ctx.card);
    sc.next_tok();
    let Some(vtok) = sc.next_tok() else {
        ctx.err(span, ".ac needs dec, oct or lin");
        return;
    };
    let vspan = sc.span(&vtok);
    let Some(var) = variation(&vtok.lc()) else {
        ctx.err(
            vspan,
            format!("expected dec, oct or lin, got `{}`", vtok.text),
        );
        return;
    };
    let (Some(points), Some(fstart), Some(fstop)) = (
        ctx.value_req(&mut sc, "number of points"),
        ctx.value_req(&mut sc, "start frequency"),
        ctx.value_req(&mut sc, "stop frequency"),
    ) else {
        return;
    };
    nl.analyses.push(Analysis::Ac {
        variation: var,
        points,
        fstart,
        fstop,
        span,
    });
}

/// `.sp DEC|OCT|LIN N FSTART FSTOP <DONOISE>` (ngspice `dot_sp`,
/// `inp2dot.c`): the `.ac` shape plus an optional integer that turns
/// on the noise outputs when it is exactly 1 (`SPsetParm`:
/// `iValue == 1`, after `IF_INTEGER` truncation).
fn dot_sp(ctx: &mut DotCtx, nl: &mut Netlist, span: Span) {
    let mut sc = Scanner::new(ctx.card);
    sc.next_tok();
    let Some(vtok) = sc.next_tok() else {
        ctx.err(span, ".sp needs dec, oct or lin");
        return;
    };
    let Some(var) = variation(&vtok.lc()) else {
        let s = sc.span(&vtok);
        ctx.err(s, format!("expected dec, oct or lin, got `{}`", vtok.text));
        return;
    };
    let (Some(points), Some(fstart), Some(fstop)) = (
        ctx.value_req(&mut sc, "number of points"),
        ctx.value_req(&mut sc, "start frequency"),
        ctx.value_req(&mut sc, "stop frequency"),
    ) else {
        return;
    };
    let donoise = ctx.value_opt(&mut sc).is_some_and(|v| v.trunc() == 1.0);
    nl.analyses.push(Analysis::Sp {
        variation: var,
        points,
        fstart,
        fstop,
        donoise,
        span,
    });
}

/// `.pss FREQ TSTAB OSCNODE <POINTS <HARMS <SCITER <STEADYCOEFF>>>>
/// <UIC>` (ngspice-47 `dot_pss`, `inp2dot.c`): the same positional
/// fields, the trailing ones optional here (ngspice requires them all
/// and reads a missing one as garbage). `UIC` may close the card.
fn dot_pss(ctx: &mut DotCtx, nl: &mut Netlist, span: Span) {
    let mut sc = Scanner::new(ctx.card);
    sc.next_tok();
    let (Some(freq), Some(tstab)) = (
        ctx.value_req(&mut sc, "fundamental frequency"),
        ctx.value_req(&mut sc, "stabilization time"),
    ) else {
        return;
    };
    let Some(node) = sc.next_tok() else {
        ctx.err(
            span,
            ".pss needs an oscillation node (ngspice's OSCNODE field)",
        );
        return;
    };
    let osc_node = node.lc();
    let mut fields = [None; 4];
    let names = [
        "points",
        "harmonics",
        "shooting iterations",
        "steady coefficient",
    ];
    let mut uic = false;
    let mut k = 0;
    while let Some(tok) = sc.peek_tok() {
        let tspan = sc.span(&tok);
        if tok.eq_ic("uic") {
            sc.next_tok();
            uic = true;
            continue;
        }
        if uic || k == fields.len() {
            sc.next_tok();
            ctx.err(tspan, format!("unknown parameter ({}) on .pss", tok.lc()));
            continue;
        }
        fields[k] = ctx.value_req(&mut sc, names[k]);
        if fields[k].is_none() {
            sc.next_tok();
        }
        k += 1;
    }
    nl.analyses.push(Analysis::Pss {
        freq,
        tstab,
        osc_node,
        points: fields[0],
        harmonics: fields[1],
        sc_iter: fields[2],
        steady_coeff: fields[3],
        uic,
        span,
    });
}

/// `.tran TSTEP TSTOP <TSTART <TMAX>> <UIC>`
fn dot_tran(ctx: &mut DotCtx, nl: &mut Netlist, span: Span) {
    let mut sc = Scanner::new(ctx.card);
    sc.next_tok();
    let (Some(tstep), Some(tstop)) = (
        ctx.value_req(&mut sc, "time step"),
        ctx.value_req(&mut sc, "stop time"),
    ) else {
        return;
    };
    let tstart = ctx.value_opt(&mut sc);
    let tmax = if tstart.is_some() {
        ctx.value_opt(&mut sc)
    } else {
        None
    };
    let mut uic = false;
    while let Some(tok) = sc.next_tok() {
        let tspan = sc.span(&tok);
        if tok.eq_ic("uic") {
            uic = true;
        } else {
            let t = tok.lc();
            ctx.err(tspan, format!("unknown parameter ({t})"));
        }
    }
    nl.analyses.push(Analysis::Tran {
        tstep,
        tstop,
        tstart,
        tmax,
        uic,
        span,
    });
}

/// `.pz NODE1 NODE2 NODE3 NODE4 CUR|VOL POL|ZER|PZ`
fn dot_pz(ctx: &mut DotCtx, nl: &mut Netlist, span: Span) {
    let mut sc = Scanner::new(ctx.card);
    sc.next_tok();
    let mut nodes = Vec::new();
    for what in ["node 1", "node 2", "node 3", "node 4"] {
        match sc.next_tok() {
            Some(t) => nodes.push(t.lc()),
            None => {
                let s = sc.here();
                ctx.err(s, format!("missing {what}"));
                return;
            }
        }
    }
    let Some(itok) = sc.next_tok() else {
        let s = sc.here();
        ctx.err(s, "missing cur/vol");
        return;
    };
    let input = match itok.lc().as_str() {
        "cur" => PzInput::Current,
        "vol" => PzInput::Voltage,
        other => {
            let s = sc.span(&itok);
            ctx.err(s, format!("expected cur or vol, got `{other}`"));
            return;
        }
    };
    let Some(wtok) = sc.next_tok() else {
        let s = sc.here();
        ctx.err(s, "missing pol/zer/pz");
        return;
    };
    let which = match wtok.lc().as_str() {
        "pol" => PzWhich::Poles,
        "zer" => PzWhich::Zeros,
        "pz" => PzWhich::Both,
        other => {
            let s = sc.span(&wtok);
            ctx.err(s, format!("expected pol, zer or pz, got `{other}`"));
            return;
        }
    };
    let nodes: [String; 4] = nodes.try_into().expect("four nodes collected");
    nl.analyses.push(Analysis::Pz {
        nodes,
        input,
        which,
        span,
    });
}

/// `.noise V(OUTPUT <,REF>) SRC DEC|LIN|OCT PTS FSTART FSTOP <PPS>`
fn dot_noise(ctx: &mut DotCtx, nl: &mut Netlist, span: Span) {
    let mut sc = Scanner::new(ctx.card);
    sc.next_tok();
    // `v ( out <, ref> )` arrives as the tokens `v out <ref>` since
    // parentheses and commas are separators — the same trick
    // `INP2dot` uses for `.nodeset`.
    let Some(vtok) = sc.next_tok() else {
        ctx.err(span, ".noise needs an output, v(node)");
        return;
    };
    if !vtok.eq_ic("v") {
        let s = sc.span(&vtok);
        ctx.err(s, ".noise output must be v(node) or v(node,ref)");
        return;
    }
    let Some(out) = sc.next_tok() else {
        let s = sc.here();
        ctx.err(s, "missing output node");
        return;
    };
    let output = out.lc();
    // The next token is either the reference node or the source.
    // Disambiguate like the C: if the token after it is dec/lin/oct,
    // this token was the source.
    let Some(t1) = sc.next_tok() else {
        let s = sc.here();
        ctx.err(s, "missing noise source");
        return;
    };
    let (output_ref, src) = match sc.peek_tok() {
        Some(t2) if variation(&t2.lc()).is_some() => (None, t1.lc()),
        _ => {
            let r = t1.lc();
            match sc.next_tok() {
                Some(srctok) => (Some(r), srctok.lc()),
                None => {
                    let s = sc.here();
                    ctx.err(s, "missing noise source");
                    return;
                }
            }
        }
    };
    let Some(vtok) = sc.next_tok() else {
        let s = sc.here();
        ctx.err(s, "missing dec, oct or lin");
        return;
    };
    let Some(var) = variation(&vtok.lc()) else {
        let s = sc.span(&vtok);
        ctx.err(s, format!("expected dec, oct or lin, got `{}`", vtok.text));
        return;
    };
    let (Some(points), Some(fstart), Some(fstop)) = (
        ctx.value_req(&mut sc, "number of points"),
        ctx.value_req(&mut sc, "start frequency"),
        ctx.value_req(&mut sc, "stop frequency"),
    ) else {
        return;
    };
    let pts_per_summary = ctx.value_opt(&mut sc);
    nl.analyses.push(Analysis::Noise {
        output,
        output_ref,
        src,
        variation: var,
        points,
        fstart,
        fstop,
        pts_per_summary,
        span,
    });
}

/// `.disto DEC|OCT|LIN NP FSTART FSTOP <F2OVERF1>`
fn dot_disto(ctx: &mut DotCtx, nl: &mut Netlist, span: Span) {
    let mut sc = Scanner::new(ctx.card);
    sc.next_tok();
    let Some(vtok) = sc.next_tok() else {
        ctx.err(span, ".disto needs dec, oct or lin");
        return;
    };
    let Some(var) = variation(&vtok.lc()) else {
        let s = sc.span(&vtok);
        ctx.err(s, format!("expected dec, oct or lin, got `{}`", vtok.text));
        return;
    };
    let (Some(points), Some(fstart), Some(fstop)) = (
        ctx.value_req(&mut sc, "number of points"),
        ctx.value_req(&mut sc, "start frequency"),
        ctx.value_req(&mut sc, "stop frequency"),
    ) else {
        return;
    };
    let f2overf1 = ctx.value_opt(&mut sc);
    nl.analyses.push(Analysis::Disto {
        variation: var,
        points,
        fstart,
        fstop,
        f2overf1,
        span,
    });
}

/// The output variable of `.tf` and `.sens`, walked like `INP2dot`
/// does: the single-letter token `v` followed by `(` and one or two
/// nodes (`V(N1)` when the character after the first node is `)`),
/// or `i` followed by the source name. Leaves the scanner after the
/// last name and returns the byte offset where it ended.
fn tf_outvar(
    ctx: &mut DotCtx,
    sc: &mut Scanner,
    span: Span,
    card: &str,
) -> Option<(OutVar, usize)> {
    let Some(tok) = sc.next_tok() else {
        ctx.err(
            span,
            format!("{card} needs an output variable, v(node) or i(vsrc)"),
        );
        return None;
    };
    let text = ctx.card.text.as_bytes();
    // The first non-blank character at or after `pos`.
    let next_char = |pos: usize| {
        text[pos.min(text.len())..]
            .iter()
            .copied()
            .find(|b| !matches!(b, b' ' | b'\t' | b','))
    };
    if tok.eq_ic("v") {
        if next_char(tok.end) != Some(b'(') {
            let s = sc.span(&tok);
            ctx.err(s, "syntax error: '(' expected after 'v'");
            return None;
        }
        let Some(n1) = sc.next_tok() else {
            let s = sc.here();
            ctx.err(s, "missing output node");
            return None;
        };
        if next_char(n1.end) == Some(b')') {
            let out = OutVar::Voltage {
                node: n1.lc(),
                reference: None,
                suffix: None,
            };
            return Some((out, n1.end));
        }
        let Some(n2) = sc.next_tok() else {
            let s = sc.here();
            ctx.err(s, "missing reference node");
            return None;
        };
        let out = OutVar::Voltage {
            node: n1.lc(),
            reference: Some(n2.lc()),
            suffix: None,
        };
        Some((out, n2.end))
    } else if tok.eq_ic("i") {
        let Some(src) = sc.next_tok() else {
            let s = sc.here();
            ctx.err(s, "missing output source");
            return None;
        };
        Some((
            OutVar::Current {
                vsrc: src.lc(),
                suffix: None,
            },
            src.end,
        ))
    } else {
        let s = sc.span(&tok);
        ctx.err(s, "syntax error: voltage or current expected");
        None
    }
}

/// `.sens OUTVAR [FILTER…] [AC DEC|OCT|LIN N FSTART FSTOP | DC]`
/// (ngspice's `dot_sens`; the 3f5 card has no filters). The filters
/// are scanned by hand on blanks because `INPgetTok` would break the
/// `*` globs: everything up to `ac` or `dc` is a filter.
fn dot_sens(ctx: &mut DotCtx, nl: &mut Netlist, span: Span) {
    let mut sc = Scanner::new(ctx.card);
    sc.next_tok();
    let Some((outvar, end)) = tf_outvar(ctx, &mut sc, span, ".sens") else {
        return;
    };
    // `while (*line && *line > ' ') ++line;` — skip the rest of the
    // output token (its closing parenthesis), then split on blanks.
    let text = ctx.card.text.as_str();
    let bytes = text.as_bytes();
    let mut pos = end;
    while pos < bytes.len() && bytes[pos] > b' ' {
        pos += 1;
    }
    let mut filters = Vec::new();
    let mut ac = None;
    loop {
        while pos < bytes.len() && bytes[pos] <= b' ' {
            pos += 1;
        }
        if pos >= bytes.len() {
            break;
        }
        let start = pos;
        while pos < bytes.len() && bytes[pos] > b' ' {
            pos += 1;
        }
        let word = text[start..pos].to_ascii_lowercase();
        if word == "dc" {
            break;
        }
        if word != "ac" {
            filters.push(word);
            continue;
        }
        let mut sc = Scanner::new(ctx.card);
        sc.seek(pos);
        let Some(vtok) = sc.next_tok() else {
            ctx.err(span, ".sens ac needs dec, oct or lin");
            return;
        };
        let Some(var) = variation(&vtok.lc()) else {
            let s = sc.span(&vtok);
            ctx.err(s, format!("expected dec, oct or lin, got `{}`", vtok.text));
            return;
        };
        let (Some(points), Some(fstart), Some(fstop)) = (
            ctx.value_req(&mut sc, "number of points"),
            ctx.value_req(&mut sc, "start frequency"),
            ctx.value_req(&mut sc, "stop frequency"),
        ) else {
            return;
        };
        ac = Some((var, points, fstart, fstop));
        break;
    }
    nl.analyses.push(Analysis::Sens {
        outvar,
        filters,
        ac,
        span,
    });
}

/// `.tf V(N1<,N2>)|I(VSRC) INSRC` (`INP2dot`).
fn dot_tf(ctx: &mut DotCtx, nl: &mut Netlist, span: Span) {
    let mut sc = Scanner::new(ctx.card);
    sc.next_tok();
    let Some((outvar, _)) = tf_outvar(ctx, &mut sc, span, ".tf") else {
        return;
    };
    let Some(src) = sc.next_tok() else {
        let s = sc.here();
        ctx.err(s, ".tf needs an input source");
        return;
    };
    nl.analyses.push(Analysis::Tf {
        outvar,
        insrc: src.lc(),
        span,
    });
}

/// `.options OPT1 OPT2 … OPT=VAL …` — `method` takes a word, the
/// rest are flags or numbers (`INPdoOpts`).
fn dot_options(ctx: &mut DotCtx, nl: &mut Netlist) {
    let mut sc = Scanner::new(ctx.card);
    sc.next_tok();
    while let Some(tok) = sc.next_tok() {
        let span = sc.span(&tok);
        let name = tok.lc();
        if STRING_OPTIONS.contains(&name.as_str()) {
            match sc.next_tok() {
                Some(v) => nl.options.push(Param {
                    name,
                    value: ParamValue::Str(v.lc()),
                    span,
                }),
                None => ctx.err(span, format!("option {name} needs a value")),
            }
            continue;
        }
        let mut nums = Vec::new();
        while let Some(v) = ctx.value_opt(&mut sc) {
            nums.push(v);
        }
        let value = match nums.len() {
            0 => ParamValue::Flag,
            1 => ParamValue::Num(nums[0]),
            _ => ParamValue::NumList(nums),
        };
        nl.options.push(Param { name, value, span });
    }
}

/// `.ic`/`.nodeset`: `V(NODE)=VAL …` seen as the tokens `v node val`.
fn dot_nodeinit(ctx: &mut DotCtx, nl: &mut Netlist, kind: NodeInitKind) {
    let mut sc = Scanner::new(ctx.card);
    sc.next_tok();
    let what = match kind {
        NodeInitKind::Ic => ".ic",
        NodeInitKind::Nodeset => ".nodeset",
    };
    while let Some(tok) = sc.next_tok() {
        let span = sc.span(&tok);
        if !tok.eq_ic("v") {
            ctx.err(span, format!("{what} syntax error: expected v(node)=value"));
            return;
        }
        let Some(node) = sc.next_tok() else {
            let s = sc.here();
            ctx.err(s, format!("{what}: missing node"));
            return;
        };
        let node = node.lc();
        let Some(value) = ctx.value_req(&mut sc, "node value") else {
            return;
        };
        nl.node_inits.push(NodeInit {
            kind,
            node,
            value,
            span,
        });
    }
}

/// `.print PRTYPE OV1 …` / `.plot PRTYPE OV1 <(PLO, PHI)> …`
fn dot_print_plot(ctx: &mut DotCtx, nl: &mut Netlist, span: Span, kind: OutputKind) {
    let flds = fields(ctx.card);
    if flds.len() < 2 {
        ctx.err(span, "missing analysis type (dc, ac, tran, noise or disto)");
        return;
    }
    let atype = ctx.card.text[flds[1].0..flds[1].1].to_ascii_lowercase();
    if !matches!(
        atype.as_str(),
        "dc" | "ac" | "tran" | "noise" | "disto" | "pz" | "pss"
    ) {
        let s = ctx.card.span_of(flds[1].0, flds[1].1);
        ctx.err(s, format!("unknown analysis type `{atype}`"));
        return;
    }
    let mut vars = Vec::new();
    for f in &flds[2..] {
        let text = &ctx.card.text[f.0..f.1];
        if text.starts_with('(') {
            // `.plot` range `(PLO, PHI)` — recognized and ignored
            // until plotting exists.
            continue;
        }
        vars.push(parse_outvar_field(ctx, *f));
    }
    if vars.is_empty() {
        ctx.err(span, "no output variables");
        return;
    }
    nl.outputs.push(Output {
        kind,
        analysis: Some(atype),
        vars,
        span,
    });
}

/// `.width out=N` (`fte/dotcards.c` keeps only `out`; `in` was for
/// card readers).
fn dot_width(ctx: &mut DotCtx, nl: &mut Netlist, span: Span) {
    let mut sc = Scanner::new(ctx.card);
    sc.next_tok();
    while let Some(tok) = sc.next_tok() {
        let tspan = sc.span(&tok);
        match tok.lc().as_str() {
            "out" => match ctx.value_opt(&mut sc) {
                Some(v) if (1.0..1e6).contains(&v) => nl.width_out = Some(v as usize),
                _ => ctx.err(tspan, ".width out needs a positive count"),
            },
            "in" => {
                ctx.value_opt(&mut sc);
            }
            other => ctx.err(tspan, format!("unknown parameter ({other})")),
        }
    }
    if nl.width_out.is_none() {
        ctx.warn(span, ".width without out= has no effect");
    }
}

/// `.save vec vec …`
fn dot_save(ctx: &mut DotCtx, nl: &mut Netlist, span: Span) {
    let flds = fields(ctx.card);
    let vars: Vec<OutVar> = flds[1..]
        .iter()
        .map(|f| parse_outvar_field(ctx, *f))
        .collect();
    if vars.is_empty() {
        ctx.err(span, ".save needs at least one vector");
        return;
    }
    nl.outputs.push(Output {
        kind: OutputKind::Save,
        analysis: None,
        vars,
        span,
    });
}

/// `.four FREQ OV1 …`
fn dot_four(ctx: &mut DotCtx, nl: &mut Netlist, span: Span) {
    let flds = fields(ctx.card);
    if flds.len() < 3 {
        ctx.err(span, ".four needs a frequency and output variables");
        return;
    }
    let Some(freq) = crate::scan::evaluate(&ctx.card.text[flds[1].0..flds[1].1]) else {
        let s = ctx.card.span_of(flds[1].0, flds[1].1);
        ctx.err(s, "expected the fundamental frequency");
        return;
    };
    let vars: Vec<OutVar> = flds[2..]
        .iter()
        .map(|f| parse_outvar_field(ctx, *f))
        .collect();
    nl.outputs.push(Output {
        kind: OutputKind::Four { freq },
        analysis: None,
        vars,
        span,
    });
}

/// Whitespace-separated fields of a card (byte ranges); unlike the
/// element scanner this keeps parentheses, which output variables
/// need (`v(1,2)` is one field).
fn fields(card: &Card) -> Vec<(usize, usize)> {
    let bytes = card.text.as_bytes();
    let mut out = Vec::new();
    let mut i = 0;
    while i < bytes.len() {
        while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'\t') {
            i += 1;
        }
        let start = i;
        while i < bytes.len() && bytes[i] != b' ' && bytes[i] != b'\t' {
            i += 1;
        }
        if i > start {
            out.push((start, i));
        }
    }
    out
}

fn parse_outvar_field(ctx: &mut DotCtx, (start, end): (usize, usize)) -> OutVar {
    let text = ctx.card.text[start..end].to_ascii_lowercase();
    let span = ctx.card.span_of(start, end);
    parse_outvar(&text, span, ctx.diags)
}

/// `v(1)`, `v(4,2)`, `vm(out)`, `vdb(5)`, `i(vin)`, plain names.
pub(crate) fn parse_outvar(text: &str, span: Span, diags: &mut Vec<Diagnostic>) -> OutVar {
    let Some(open) = text.find('(') else {
        return OutVar::Raw(text.to_string());
    };
    let Some(inner) = text[open..]
        .strip_prefix('(')
        .and_then(|t| t.strip_suffix(')'))
    else {
        diags.push(Diagnostic::warning(
            format!("`{text}` looks like an output variable but has no closing parenthesis"),
            span,
        ));
        return OutVar::Raw(text.to_string());
    };
    let head = &text[..open];
    let (is_v, suffix_text) = match head.as_bytes().first() {
        Some(b'v') => (true, &head[1..]),
        Some(b'i') => (false, &head[1..]),
        _ => return OutVar::Raw(text.to_string()),
    };
    let suffix = match suffix_text {
        "" => None,
        "r" => Some(AcSuffix::Real),
        "i" => Some(AcSuffix::Imag),
        "m" => Some(AcSuffix::Mag),
        "p" => Some(AcSuffix::Phase),
        "db" => Some(AcSuffix::Db),
        _ => return OutVar::Raw(text.to_string()),
    };
    let parts: Vec<&str> = inner.split(',').map(str::trim).collect();
    if is_v {
        match parts.as_slice() {
            [node] if !node.is_empty() => OutVar::Voltage {
                node: node.to_string(),
                reference: None,
                suffix,
            },
            [node, reference] if !node.is_empty() && !reference.is_empty() => OutVar::Voltage {
                node: node.to_string(),
                reference: Some(reference.to_string()),
                suffix,
            },
            _ => {
                diags.push(Diagnostic::warning(
                    format!("malformed voltage output `{text}`"),
                    span,
                ));
                OutVar::Raw(text.to_string())
            }
        }
    } else {
        match parts.as_slice() {
            [vsrc] if !vsrc.is_empty() => OutVar::Current {
                vsrc: vsrc.to_string(),
                suffix,
            },
            _ => {
                diags.push(Diagnostic::warning(
                    format!("malformed current output `{text}`"),
                    span,
                ));
                OutVar::Raw(text.to_string())
            }
        }
    }
}