/** * SPICE netlist tokenizer + parser (Wave A7) — the documented-subset grammar * and its converter onto the engine's SimCircuit shape. * * THE DOCUMENTED SUBSET (everything else is a line-numbered hard error): * * - Line 1 is the title, always (classic SPICE — it is never parsed as a * card, so a netlist whose first line is an element loses that element by * design, exactly as ngspice would). * - Comments: full-line `*`; end-of-line `;` anywhere, `$` when at the start * of a line or preceded by whitespace (the ngspice rule — `$` may be part * of a name otherwise). Continuations: a line starting with `+` appends to * the previous card; comment/blank lines in between do not break the chain. * - Everything is case-insensitive (cards are lowercased whole; original * text is preserved for diagnostics). `(`, `)` and `,` are token * separators; `=` is its own token. * - Numbers: optional sign, decimal, optional e-notation, then an optional * engineering suffix f/p/n/u/m/k/meg/g/t (checked longest-first so `meg` * never reads as milli); any remaining ALPHABETIC tail is a unit label and * is ignored (`10kOhm`, `5V` — SPICE-compatible, including the `10f` = * 10 femto trap). `mil` is rejected outright rather than silently parsing * as milli-with-ignored-tail, which would be off by 39x from SPICE. * - Elements: R/C/L (values must be positive — ngspice tolerates negative R, * these stamps do not — and only the positional value form parses: the * ngspice `R=`/`C=`/`L=` inline form is rejected loudly; C and L accept * IC=), K (couples two named L elements in the SAME scope — a top-level K * naming a subcircuit-internal inductor is an error, as in ngspice), * V (DC value, `DC v`, `SIN(vo va freq [td])` — FREQ must be positive, * and a negative VA maps exactly onto |VA| with a 180-degree phase * because the engine's signal_gen clamps negative amplitudes to 0 — * `PULSE(v1 v2 td tr tf pw per)` — all seven PULSE values are required * because SPICE's defaults come from .tran, which the subset does not * retro-apply), I (DC only), D/Q/M/J (each requires a .model reference; * M takes the 4-node SPICE form plus W=/L=), X (subcircuit * instantiation). * - `AC mag` on a V or I element designates THE small-signal input (exactly * one per netlist, and .ac requires one — checked at parse time); `AC 0` * is ngspice's "no AC drive" and is accepted-but-ignored with a warning; * an AC phase argument is not supported. * - .model types D, NPN, PNP, NMOS, PMOS, NJF, PJF (parameter mapping and * its per-device fidelity notes live in ./models.ts). Models are global * and top-level only; elements may reference models defined later. * - .subckt/.ends definitions at TOP LEVEL only (bodies may instantiate * other subcircuits to any depth — expansion is recursive with a depth * cap of 32 so a self-referential definition fails with a clear error * instead of a stack overflow). Expansion is a parse-time macro pass: * element ids are namespaced "x1.r1", internal nets "x1:n1", and node "0" * stays global, all per standard SPICE scoping. * - Directives: .op, .tran tstep tstop, .dc src start stop step, * .ac dec|lin n fstart fstop, .ic v(node)=value... (an entry naming node * 0 is dropped with a warning — ngspice ignores it too; in an element-IC * [UIC-style] run node entries act only through the capacitor projection, * so an entry on a node with no capacitor terminal warns that it is * dropped), .temp t (at most once), .end. * Two runner-side grid caveats (both documented in ./run.ts): a .tran * tstop that is not a whole multiple of tstep truncates the fixed-step * window (never overshoots, warns); a .ac dec sweep uses the pure * fstart*10^(k/n) lattice, whose tail differs from ngspice's * land-on-fstop dec grid when fstop is off-lattice. * .param is NOT supported (explicit error naming it — silently treating * parameter expressions as literals would corrupt every derived value). * * CONVERSION RULES: each SPICE node becomes a chain of wires pin[i] -> * pin[i+1] over the pins attached to it, which graph.ts unions into one net * (the engine has no first-class "net" input, only wires). A K card rewrites * its two L elements into ONE coupled_inductor (the engine models coupling * as a single 2x2 companion, not as a constraint between two inductors), at * the first L's position in component order so stamp order stays the * netlist's. Reference/ground is NOT chosen here: the engine picks its own * MNA reference (graph.ts source-neg rule) and the run layer normalizes all * reported voltages to V(node) - V("0"), so parse order never changes * results. * * PURITY: no filesystem/DOM access and no runtime engine imports (the * SimCircuit import is type-only) — the parser must be loadable anywhere the * engine's pure helpers are, including workers and tests that never touch a * live engine. */ import type { SimCircuit } from "../sim-engine.js"; import { type SpiceModelCard } from "./models.js"; export type { SpiceModelCard, SpiceModelType } from "./models.js"; /** One component pin — the converter's anchor for a SPICE node's net. */ export interface SpicePinRef { componentId: string; pinId: string; } export interface SpiceAnalysisOp { kind: "op"; line: number; } export interface SpiceAnalysisTran { kind: "tran"; /** Fixed engine step AND output interval (the subset does not separate them). */ tstepS: number; /** Window end. The runner never samples past it: a tstop that is not a * whole multiple of tstep truncates to floor(tstop/tstep) steps, with a * warning (see run.ts). */ tstopS: number; line: number; } export interface SpiceAnalysisDc { kind: "dc"; /** Lowercased element name of the swept V or I source. */ source: string; start: number; stop: number; step: number; line: number; } export interface SpiceAnalysisAc { kind: "ac"; variation: "dec" | "lin"; /** dec: points per decade; lin: total points. */ n: number; fstartHz: number; fstopHz: number; line: number; } export type SpiceAnalysis = SpiceAnalysisOp | SpiceAnalysisTran | SpiceAnalysisDc | SpiceAnalysisAc; /** * Initial-condition record. Element IC= assignments are UIC-style seeds for * the engine's cap/inductor state maps; .ic node voltages are kept separate * because their SPICE meaning differs by mode (the runner documents how each * is applied). capVoltsFromNodeIc is the parser's projection of .ic node * voltages onto capacitor terminal pairs (unlisted nodes read as 0), used * only when a run is already UIC-style — computed here because only the * parser still knows which SPICE nodes each capacitor touches. The * projection is also the ONLY way .ic node voltages act in that mode: an * .ic entry on a node with no capacitor terminal cannot be honored there * (ngspice UIC would force it into the initial solve), so the parser warns * about the drop instead of diverging silently. */ export interface SpiceInitialConditions { /** capacitor component id -> volts (pin a - pin b), from C-line IC=. */ capVolts: Map; /** state-map key -> amps (winding current), from L-line IC=. Keys are the * inductor component id, or ":1"/":2" after a K merge. */ indAmps: Map; /** SPICE node -> volts, from .ic cards. */ nodeVolts: Map; /** capacitor component id -> volts derived from .ic node entries. */ capVoltsFromNodeIc: Map; } export interface ParsedNetlist { /** Line 1 of the netlist, verbatim (trimmed). */ title: string; /** Engine-shaped circuit: components plus one wire chain per SPICE node. */ circuit: SimCircuit; /** SPICE node -> a representative attached pin, in first-appearance order. * Resolving that pin's net id after load() locates the node's net. */ nodeNets: Map; /** .model cards by lowercased name. */ models: Map; /** Analyses in declaration order (at most one of each kind). */ analyses: SpiceAnalysis[]; /** Collected non-fatal findings (unsupported .model params, single-pin * nodes, ignored MOS bulk connections, ...). */ warnings: string[]; /** The one AC-designated source, if any element carried an AC spec. */ acInput: { componentId: string; magnitude: number; } | null; initialConditions: SpiceInitialConditions; } /** Parse failure carrying the 1-based netlist line and the offending card. */ export declare class SpiceParseError extends Error { readonly line: number; readonly card: string; constructor(line: number, card: string, message: string); } /** * Parse one lowercased token as a SPICE number. Returns null (never throws) * so call sites can decide between "this must be a number" errors and * "numbers end here" scans (SIN/PULSE argument collection). * * A suffix is applied as a DECIMAL EXPONENT SHIFT — the value is recomposed * as "e" and parsed once — never as a float * multiplication: 20 * 1e-6 lands one ULP away from the decimal literal * 20e-6, so multiplying would make "20u" and "20e-6" describe two different * circuits and break bit-exact cross-checks against natively built ones. */ export declare function parseSpiceNumber(token: string): number | null; export declare function parseSpiceNetlist(netlistText: string): ParsedNetlist;