general_spice_core/lib.rs
1#![warn(missing_docs)]
2//! `general_spice_core` — a dialect-agnostic parser and symbol-resolution engine
3//! for SPICE-family circuit netlists (ngspice and Xyce today; a third proprietary dialect
4//! planned once reference documentation is available).
5//!
6//! This crate does not simulate circuits. It turns netlist *text* into
7//! structured data an editor or tool can use for diagnostics, hover,
8//! go-to-definition, and completion — the kind of thing a language server
9//! needs, without being tied to the Language Server Protocol itself. It is
10//! consumed two ways in practice: embedded directly as a library (e.g. from
11//! a Tauri app's Rust backend, calling straight into these functions with
12//! no IPC layer involved), or wrapped by a separate `tower-lsp`-based
13//! binary that speaks LSP over stdio for editors.
14//!
15//! # Is this crate right for your use case?
16//!
17//! Yes, if you want to: parse ngspice or Xyce netlist text into a
18//! structured AST; detect duplicate `.subckt`/`.model` names, undefined
19//! subcircuit/model references, or circular `.subckt`/`.include` chains;
20//! resolve `.param` scoping (including the dialect-specific differences —
21//! see `docs/GRAMMAR.md` in the repository); parse SPICE expressions
22//! (arithmetic, behavioral B/E/G-source forms) into a typed tree; or
23//! resolve multi-file `.include`/`.lib` netlists into one merged document.
24//!
25//! No, if you want to: actually *simulate* a circuit (this crate has no
26//! solver — pair it with a real ngspice/Xyce process for that), fully
27//! validate every SPICE statement type (some statements are captured
28//! structurally as raw text rather than semantically modeled — see
29//! `docs/GRAMMAR.md`'s phase plan for what's covered), or work with
30//! that third proprietary dialect's netlists (not yet supported).
31//!
32//! # Architecture
33//!
34//! One common core plus per-dialect overlays — never two independent
35//! grammars, and never one grammar with dialect checks scattered through
36//! shared logic. Concretely:
37//!
38//! - [`dialect`] — the [`Dialect`] enum and the device-letter overlay
39//! table. Some device letters mean different things in each dialect
40//! (`P` is a coupled-multiconductor line in ngspice but an S-parameter
41//! port device in Xyce); resolving that ambiguity is this module's job,
42//! done once, rather than re-derived by every caller.
43//! - [`lexer`] — dialect-aware comment stripping and line-continuation
44//! joining, run before any statement-level parsing.
45//! - [`ast`] — the common-core [`ast::Statement`] enum, shared by both
46//! dialects. Dialect-specific *meaning* lives in the overlay tables, not
47//! as extra AST variants.
48//! - [`parser`] — turns preprocessed lines into [`ast::Statement`]s. Two
49//! entry points: [`parser::parse`] for a statement fragment (what
50//! every unit test in this crate uses), and [`parser::parse_document`]
51//! for a whole real file (which has a mandatory title line — see that
52//! function's docs for why the distinction matters).
53//! - [`expr`] — SPICE expression parsing. Not one grammar: ngspice alone
54//! has a compile-time grammar (`.param`/`.func`/brace-expressions) and a
55//! separate runtime grammar (B/E/G-source expressions) with a
56//! genuinely different function set and operator semantics. Xyce has one
57//! unified grammar instead, but with context-dependent restrictions on
58//! what an expression may reference. [`expr::diagnostics`] flags the
59//! cross-dialect false cognates (`^` means power in ngspice, boolean XOR
60//! in Xyce; `log()` is natural log in ngspice, base-10 in Xyce).
61//! - [`symbols`] — scope-tree construction ([`symbols::scope`]) and the
62//! diagnostic passes built on it: name uniqueness
63//! ([`symbols::uniqueness`]), `.subckt` call resolution with circular-
64//! reference detection ([`symbols::subckt_resolution`]), `.model`
65//! reference resolution ([`symbols::model_resolution`]), and dialect-
66//! specific `.param` scope chains ([`symbols::ngspice_param_scope`],
67//! [`symbols::xyce_param_scope`]).
68//! - [`mod@include`] — multi-file `.include`/`.lib` resolution
69//! ([`include::graph`]), behind a [`include::resolve::FileSystem`] trait
70//! so it's testable without touching real disk.
71//!
72//! For the full grammar reference this crate implements against —
73//! including exactly what's common between ngspice and Xyce, what
74//! diverges, and why — see `docs/GRAMMAR.md` in the repository root. For
75//! what's implemented vs. planned, see `progress.core.yaml`.
76//!
77//! # Quick start: parsing a single file
78//!
79//! ```
80//! use general_spice_core::{ast::Statement, lexer, parser, Dialect};
81//!
82//! let source = "\
83//! Example RC circuit
84//! R1 1 0 1k
85//! C1 1 0 10n
86//! .end
87//! ";
88//!
89//! let lines = lexer::preprocess(source, Dialect::Ngspice);
90//! // parse_document (not parse) because this is a whole real file: the
91//! // first line is always the title, per the SPICE convention both
92//! // dialects share.
93//! let results = parser::parse_document(&lines, Dialect::Ngspice);
94//!
95//! let mut device_names = Vec::new();
96//! for result in &results {
97//! if let Ok(Statement::ElementInstance(ei)) = result {
98//! device_names.push(ei.name.as_str());
99//! }
100//! }
101//! assert_eq!(device_names, vec!["R1", "C1"]);
102//! ```
103//!
104//! # Quick start: diagnostics (undefined subcircuit reference)
105//!
106//! ```
107//! use general_spice_core::{ast::Statement, lexer, parser, symbols, Dialect};
108//!
109//! let source = "\
110//! Circuit with a typo'd subckt reference
111//! X1 in out amplifier
112//! .end
113//! ";
114//!
115//! let lines = lexer::preprocess(source, Dialect::Ngspice);
116//! let parsed = parser::parse_document(&lines, Dialect::Ngspice);
117//! let statements: Vec<Statement> = parsed.into_iter().flatten().collect();
118//!
119//! let tree = symbols::scope::build_scope_tree(&statements)
120//! .expect("well-formed .subckt/.ends nesting");
121//! let diagnostics = symbols::subckt_resolution::resolve_subckt_calls(&tree, Dialect::Ngspice);
122//!
123//! assert_eq!(diagnostics.len(), 1);
124//! assert!(diagnostics[0].message.contains("undefined subcircuit"));
125//! ```
126//!
127//! # Quick start: multi-file `.include` resolution
128//!
129//! ```
130//! use general_spice_core::include::graph::resolve_includes;
131//! use general_spice_core::include::resolve::FakeFileSystem;
132//! use general_spice_core::include::source_map::SourceMap;
133//! use general_spice_core::Dialect;
134//! use std::path::Path;
135//!
136//! let mut fs = FakeFileSystem::new();
137//! fs.insert(
138//! "/top.cir",
139//! "top-level circuit\nR1 1 2 100\n.include /parts.cir\n.end\n",
140//! );
141//! fs.insert("/parts.cir", "C1 2 0 10n\n");
142//!
143//! let mut source_map = SourceMap::new();
144//! let (statements, diagnostics) =
145//! resolve_includes(Path::new("/top.cir"), &fs, Dialect::Ngspice, &mut source_map);
146//!
147//! assert!(diagnostics.is_empty());
148//! // title (Comment) + R1 (top.cir) + C1 (spliced in from parts.cir) +
149//! // .end (not yet semantically modeled, captured as Unrecognized) —
150//! // all merged in document order.
151//! assert_eq!(statements.len(), 4);
152//! ```
153//!
154//! `FakeFileSystem` is the same in-memory test double this crate's own
155//! test suite uses; swap in a real [`include::resolve::FileSystem`]
156//! implementation backed by `std::fs` to resolve real files.
157
158pub mod ast;
159pub mod dialect;
160pub mod expr;
161pub mod include;
162pub mod lexer;
163pub mod parser;
164pub mod symbols;
165
166pub use dialect::Dialect;