Skip to main content

gsim_py/
lib.rs

1//! PyO3 bindings for `gsim-core`.
2//!
3//! # Interface design
4//!
5//! Every function here is **stateless and JSON-in/JSON-out**: it takes Python `str` (JSON text),
6//! parses it with `serde_json`, calls straight into `gsim-core`, and returns Python `str` (JSON
7//! text) or raises a `ValueError` carrying the real Rust error's `Display` message. There is no
8//! stateful Rust object (e.g. `ModelBuilder`) exposed across the FFI boundary — a caller builds a
9//! `Model` up incrementally by round-tripping its JSON through successive calls
10//! (`new_model` -> `add_block` -> `connect` -> ... -> `save_document`). This matches `gsim-core`'s
11//! own internal philosophy of JSON as the interchange format everywhere, avoids needing GC/
12//! lifetime integration for a wrapped Rust object living inside Python's object model, and keeps
13//! this crate a thin wrapper rather than a second place schema/validation/layout logic could
14//! drift. `crates/gsim-wasm` exposes the same JSON contracts to JavaScript.
15//!
16//! No function here reimplements schema, validation, or layout logic — see `AGENTS.md`'s "one
17//! implementation, thin bindings" rule. A couple of small additive helpers were added to
18//! `gsim-core` itself to support this thin-wrapper shape without duplicating shape definitions in
19//! this crate: `Deserialize` on `document::NewBlockSpec`/`document::ConnectOptions`, `Serialize`
20//! on `contract::ValidationFailure`, and `Serialize`/`Deserialize` on `layout::Rect` — see each
21//! item's doc comment in `gsim-core` for why.
22
23use gsim_core::compile::{compile as compile_model, CompileError};
24use gsim_core::contract::{self, ComponentContract, ContractRegistry};
25use gsim_core::document::{
26    BuilderError, CompatFailure, ConnectOptions, Endpoint, GsimSchDocument, Model, ModelBuilder,
27    NewBlockSpec, NewSubcktInstanceSpec, SubcktDef, SubcktError,
28};
29use gsim_core::layout::{self, Axis, LayoutInput, Rect};
30use pyo3::exceptions::PyValueError;
31use pyo3::prelude::*;
32use serde::{Deserialize, Serialize};
33use serde_json::{Map, Value};
34use std::collections::HashMap;
35
36/// Converts any `Display`-able error into a Python `ValueError` carrying its real message —
37/// never an opaque panic, and never a generic message that swallows which specific error variant
38/// occurred.
39fn to_py_err<E: std::fmt::Display>(e: E) -> PyErr {
40    PyErr::new::<PyValueError, _>(e.to_string())
41}
42
43/// Like [`to_py_err`], but for `BuilderError` specifically: prefixes the real `Display` message
44/// with the variant's canonical keyword ("duplicate", "dangling", "cross-paradigm", ...) so a
45/// caller can reliably match on *which* case occurred from the message text alone, even though
46/// `BuilderError`'s own `Display` impl phrases some variants (`CrossParadigm`, `DanglingWire`)
47/// descriptively rather than using that exact word. The full underlying message always follows,
48/// unmodified — this never swallows detail, only adds a stable keyword in front of it.
49fn builder_err_to_py(e: BuilderError) -> PyErr {
50    let keyword = match &e {
51        BuilderError::DuplicateId(_) => "duplicate",
52        BuilderError::DanglingWire { .. } => "dangling",
53        BuilderError::CrossParadigm { .. } => "cross-paradigm",
54        // One keyword per `port-compat.ts` reason rather than a single "port-incompatible":
55        // the three cases need different fixes (drop a v3-reserved kind / correct the wire kind
56        // / remove the second driver), so a caller branching on them is the expected use. Same
57        // sub-matching precedent as `Subckt(CyclicDefReference)` below.
58        BuilderError::PortIncompatible(inc) => match &inc.failure {
59            CompatFailure::ReservedKind { .. } => "port-reserved-kind",
60            CompatFailure::KindMismatch { .. } => "port-kind-mismatch",
61            CompatFailure::FanInOnSignal { .. } => "port-fan-in-on-signal",
62            CompatFailure::DimMismatch { .. } => "port-dim-mismatch",
63        },
64        BuilderError::UnknownBlock(_) => "unknown-block",
65        BuilderError::Block(_) => "invalid-block",
66        BuilderError::UnknownSubcktDef(_) => "unknown-subckt-def",
67        BuilderError::Subckt(SubcktError::CyclicDefReference { .. }) => "cyclic-subckt-def",
68        BuilderError::Subckt(_) => "invalid-subckt",
69    };
70    PyErr::new::<PyValueError, _>(format!("{keyword}: {e}"))
71}
72
73/// Same stable-keyword-prefix idea as [`builder_err_to_py`], for the compiler's errors.
74fn compile_err_to_py(e: CompileError) -> PyErr {
75    let keyword = match &e {
76        CompileError::UnknownType { .. } => "unknown-type",
77        CompileError::UnknownTarget(_) => "unknown-target",
78        CompileError::FloatingPort { .. } => "floating-port",
79        CompileError::UnconnectedRef { .. } => "unconnected-ref",
80        CompileError::MissingParam { .. } => "missing-param",
81        CompileError::UnknownSubcktDef { .. } => "unknown-subckt-def",
82        CompileError::UnconnectedSubcktPort { .. } => "unconnected-subckt-port",
83        CompileError::UnknownVariant { .. } => "unknown-variant",
84        CompileError::VectorOutputPort { .. } => "vector-output-port",
85        CompileError::IndexedRefArity { .. } => "indexed-ref-arity",
86        CompileError::UnresolvedFromTag { .. } => "unresolved-from-tag",
87        CompileError::AmbiguousFromTag { .. } => "ambiguous-from-tag",
88        CompileError::CyclicFromTag { .. } => "cyclic-from-tag",
89        CompileError::RoutingKindUnsupported { .. } => "routing-kind-unsupported",
90        CompileError::RefNotAnOutput { .. } => "ref-not-an-output",
91        CompileError::DuplicateName(_) => "duplicate-name",
92        CompileError::DuplicateNet(_) => "duplicate-net",
93        CompileError::BadRating { .. } => "bad-rating",
94    };
95    PyErr::new::<PyValueError, _>(format!("{keyword}: {e}"))
96}
97
98fn parse_json<T: for<'de> Deserialize<'de>>(text: &str, what: &str) -> PyResult<T> {
99    serde_json::from_str(text).map_err(|e| to_py_err(format!("invalid {what} JSON: {e}")))
100}
101
102fn to_json<T: Serialize>(value: &T) -> PyResult<String> {
103    serde_json::to_string(value).map_err(to_py_err)
104}
105
106#[pyfunction]
107fn version() -> &'static str {
108    gsim_core::version()
109}
110
111/// Parses `contract_json` as a `ComponentContract` and `params_json` as a JSON object of
112/// parameter values, evaluates it (GSF v2), and returns the resulting `EvaluatedSymbol`
113/// (`{"bbox": [w, h], "ports": [...], "primitives": [...]}`) as JSON.
114/// What this engine can compile, as JSON — see `gsim_core::compile::capabilities`.
115///
116/// The front end renders this instead of keeping its own list of supported types and their
117/// parameters. That list used to exist and had drifted to the point where none of the 143
118/// catalogue types matched it, so every block reported "not supported by the simulator".
119#[pyfunction]
120fn capabilities() -> String {
121    gsim_core::compile::capabilities::capabilities_json()
122}
123
124/// The component library: everything a front end needs to show a palette, plus whether this
125/// engine can compile each component.
126///
127/// The front end used to keep its own catalogue of components beside this -- labels, port
128/// geometry, parameter names and defaults -- and the two drifted until a switch's parameters
129/// disagreed about whether they were resistances or conductances. There is one description
130/// now, and it is this one.
131#[pyfunction]
132fn catalog() -> String {
133    gsim_core::compile::library::catalog_json()
134}
135
136#[pyfunction]
137fn evaluate_component(contract_json: &str, params_json: &str) -> PyResult<String> {
138    let contract: ComponentContract = parse_json(contract_json, "contract")?;
139    let params: Map<String, Value> = parse_json(params_json, "params")?;
140    let evaluated = contract::evaluate_component(&contract, &params).map_err(to_py_err)?;
141    to_json(&evaluated)
142}
143
144/// Returns a JSON array of `{"parameter": ..., "message": ...}` failures (empty array `"[]"`
145/// means every validated parameter passed). Never raises for validation failures themselves —
146/// only for malformed input JSON.
147#[pyfunction]
148fn validate_parameters(contract_json: &str, params_json: &str) -> PyResult<String> {
149    let contract: ComponentContract = parse_json(contract_json, "contract")?;
150    let params: Map<String, Value> = parse_json(params_json, "params")?;
151    let failures = contract::validate_parameters(&contract, &params);
152    to_json(&failures)
153}
154
155/// Returns a fresh, empty `Model` as JSON.
156#[pyfunction]
157fn new_model(id: &str, name: &str, grid: i64) -> PyResult<String> {
158    to_json(&Model::new(id, name, grid))
159}
160
161#[derive(Serialize)]
162struct AddBlockResult {
163    model: Model,
164    block_id: String,
165}
166
167/// `spec_json` matches `NewBlockSpec`'s JSON shape (`type`, `paradigm`, `domain`, `fidelity?`,
168/// `position`, `rotation`, `mirror?`, `params?`, `ic?`, `ratings?`, `label?`,
169/// `comment_before?`, `comment_after?`, `id?`). `ratings` carries datasheet limits on the
170/// component — `{"i_max": 60, "on_violation": "stop"}` — emitted as trailing fields on its
171/// device line; they are a sibling of `params` so that changing a component's fidelity tier
172/// cannot strip them, and `compile` refuses one the engine would (a current limit on a device
173/// with no branch current, a modifier with no limit beside it).
174/// `comment_before`/`comment_after` are lists of comment lines (a
175/// single string containing newlines is split too) emitted as `*`-prefixed SPICE comment lines
176/// immediately above/below this block's card(s) by `compile`. Returns
177/// `{"model": <updated Model JSON>, "block_id": "<assigned id>"}`. Raises with the real
178/// `BuilderError`/`BlockError` message (duplicate id, invalid id/type pattern, invalid rotation)
179/// on failure.
180#[pyfunction]
181fn add_block(model_json: &str, spec_json: &str) -> PyResult<String> {
182    let model: Model = parse_json(model_json, "model")?;
183    let spec: NewBlockSpec = parse_json(spec_json, "block spec")?;
184    let mut builder = ModelBuilder::from_model(model);
185    let block_id = builder.add_block(spec).map_err(builder_err_to_py)?;
186    to_json(&AddBlockResult {
187        model: builder.into_model(),
188        block_id,
189    })
190}
191
192#[derive(Serialize)]
193struct AddSubcktDefResult {
194    model: Model,
195    def_id: String,
196}
197
198/// Adds a reusable SPICE `.SUBCKT` definition to the model.
199///
200/// **Shared JSON contract** (identical in `gsim-wasm`'s `addSubcktDef`):
201/// `def_json` is a `SubcktDef` — `{"id", "name", "ports": [{"id", "kind"}], "params"?,
202/// "blocks"?, "wires"?, "instances"? : [{"id", "def_ref", "connections"?, "params"?}]}`.
203/// Returns `{"model": <updated Model JSON>, "def_id": "<id>"}`, mirroring `add_block`'s
204/// `{"model", "block_id"}` shape. Raises on an invalid id pattern (`invalid-subckt: ...`), an
205/// invalid port kind (`invalid-subckt: ...`), a duplicate def id (`duplicate: ...`), or a
206/// cyclic `def_ref` graph (`cyclic-subckt-def: Cyclic SubcktDef reference: a -> b -> a`).
207#[pyfunction]
208fn add_subckt_def(model_json: &str, def_json: &str) -> PyResult<String> {
209    let model: Model = parse_json(model_json, "model")?;
210    let def: SubcktDef = parse_json(def_json, "subckt def")?;
211    let mut builder = ModelBuilder::from_model(model);
212    let def_id = builder.add_subckt_def(def).map_err(builder_err_to_py)?;
213    to_json(&AddSubcktDefResult {
214        model: builder.into_model(),
215        def_id,
216    })
217}
218
219/// Instantiates an existing `SubcktDef` as a top-level `spice-subckt` block.
220///
221/// **Shared JSON contract** (identical in `gsim-wasm`'s `instantiateSubckt`): `spec_json`
222/// matches `NewSubcktInstanceSpec` — `{"def_ref", "position": [x, y], "rotation"?, "domain"?,
223/// "fidelity"?, "mirror"?, "params"?, "label"?, "comment_before"?, "comment_after"?, "id"?}`.
224/// Returns
225/// `{"model": <updated Model JSON>, "block_id": "<assigned id>"}`, the same shape `add_block`
226/// returns. The created block's wireable ports are exactly the referenced def's `ports[].id`
227/// list — wire them with ordinary `connect` calls. Raises `unknown-subckt-def: ...` if
228/// `def_ref` names no def, `duplicate: ...` on a colliding block id.
229#[pyfunction]
230fn instantiate_subckt(model_json: &str, spec_json: &str) -> PyResult<String> {
231    let model: Model = parse_json(model_json, "model")?;
232    let spec: NewSubcktInstanceSpec = parse_json(spec_json, "subckt instance spec")?;
233    let mut builder = ModelBuilder::from_model(model);
234    let block_id = builder
235        .instantiate_subckt(spec)
236        .map_err(builder_err_to_py)?;
237    to_json(&AddBlockResult {
238        model: builder.into_model(),
239        block_id,
240    })
241}
242
243#[derive(Serialize)]
244struct CompileResult {
245    netlist: String,
246    notes: Vec<String>,
247    /// The document-to-netlist map — see `gsim_core::compile::provenance`. Carried across the
248    /// boundary rather than re-derived, because a consumer cannot re-derive it: the device
249    /// letter is prefixed onto a block id only when the id does not already start with it, so
250    /// `load` and `Rload` both compile to `Rload`.
251    provenance: gsim_core::compile::Provenance,
252}
253
254/// Compiles a `Model` into netlist text for `target` (currently only `"general-simulator"`).
255///
256/// **Shared JSON contract** (identical in `gsim-wasm`'s `compile`): returns
257/// `{"netlist": "<text>", "notes": ["<info-level compiler decision>", ...], "provenance":
258/// {"elements": [{"element": "<netlist name>", "blocks": ["<block id>", ...], "role":
259/// "element"|"block"|"element_and_block"|"part"|"instance", "suffix"?, "def"?}, ...],
260/// "nets": [{"net": "<node name>", "ports": [{"blocks": [...], "port": "<port id>"}, ...]},
261/// ...]}}`. Raises a
262/// `ValueError` whose message is keyword-prefixed the same way the builder errors are
263/// (`duplicate-name:`, `duplicate-net:`, `unknown-type:`, `unknown-target:`, `floating-port:`, `unconnected-ref:`,
264/// `missing-param:`, `unknown-subckt-def:`, `unconnected-subckt-port:`, `unknown-variant:`, `vector-output-port:`,
265/// `indexed-ref-arity:`, `unresolved-from-tag:`, `ambiguous-from-tag:`, `cyclic-from-tag:`,
266/// `routing-kind-unsupported:`),
267/// with the real underlying message following unmodified.
268#[pyfunction]
269fn compile(model_json: &str, target: &str) -> PyResult<String> {
270    let model: Model = parse_json(model_json, "model")?;
271    let out = compile_model(&model, target).map_err(compile_err_to_py)?;
272    to_json(&CompileResult {
273        netlist: out.netlist,
274        notes: out.notes,
275        provenance: out.provenance,
276    })
277}
278
279/// Removes a block and cascades to every wire touching it. Returns the updated `Model` JSON.
280#[pyfunction]
281fn remove_block(model_json: &str, block_id: &str) -> PyResult<String> {
282    let model: Model = parse_json(model_json, "model")?;
283    let mut builder = ModelBuilder::from_model(model);
284    builder.remove_block(block_id);
285    to_json(&builder.into_model())
286}
287
288/// Sets one parameter on one block. Returns the updated `Model` JSON. Raises if `block_id`
289/// doesn't exist.
290#[pyfunction]
291fn set_param(model_json: &str, block_id: &str, name: &str, value_json: &str) -> PyResult<String> {
292    let model: Model = parse_json(model_json, "model")?;
293    let value: Value = parse_json(value_json, "value")?;
294    let mut builder = ModelBuilder::from_model(model);
295    builder
296        .set_param(block_id, name, value)
297        .map_err(builder_err_to_py)?;
298    to_json(&builder.into_model())
299}
300
301/// Adds a model-level (schematic-wide) parameter. Returns the updated `Model` JSON. Raises on a
302/// duplicate parameter name.
303#[pyfunction]
304fn add_model_param(model_json: &str, name: &str, value_json: &str) -> PyResult<String> {
305    let model: Model = parse_json(model_json, "model")?;
306    let value: Value = parse_json(value_json, "value")?;
307    let mut builder = ModelBuilder::from_model(model);
308    builder
309        .add_model_param(name, value)
310        .map_err(builder_err_to_py)?;
311    to_json(&builder.into_model())
312}
313
314#[derive(Serialize)]
315struct ConnectResult {
316    model: Model,
317    wire_id: String,
318}
319
320/// `from_json`/`to_json` are `{"block": "...", "port": "..."}` endpoints; `opts_json` matches
321/// `ConnectOptions` (`waypoints?`, `net?`, `id?`, `pinned?`, `label?`, all optional -- `"{}"` is a
322/// valid payload). Returns `{"model": <updated Model JSON>, "wire_id": "<assigned id>"}`. Raises
323/// with the real `BuilderError` message on failure -- the message text always names the specific
324/// case ("dangling", "cross-paradigm", "duplicate") rather than a generic "connect failed", since
325/// `BuilderError`'s `Display` impl already does this and this wrapper does not paper over it.
326///
327/// Beyond the block-level cross-paradigm boundary, the per-port §8.1/§8.2 rules in
328/// `gsim_core::document::port_compat` also apply, raising with the keyword
329/// `port-reserved-kind`, `port-kind-mismatch`, `port-fan-in-on-signal` or `port-dim-mismatch`.
330///
331/// `contracts_json` is optional and defaults to none. When supplied it is a
332/// `{"<block type>": <ComponentContract>, ...}` object -- the same contract shape
333/// `evaluate_component` takes, one entry per block `type` used in the model. Supplying it lets
334/// the per-port check resolve each endpoint's real `kind` and `dim` from the block's own
335/// `params` instead of approximating from the block's `domain`, which is what makes
336/// `port-kind-mismatch` exact for ordinary components and makes `port-dim-mismatch` possible at
337/// all. **Omitting it changes nothing that used to work**: an unregistered type keeps the
338/// coarser `domain`-based check.
339///
340/// It is passed per call rather than registered once because every function in this module is
341/// stateless JSON-in/JSON-out -- there is no session object to hold a registry, and putting one
342/// in the `Model` would write a caller's component library into the saved document. A Python
343/// caller builds the dict once and passes it to each `connect`.
344#[pyfunction]
345#[pyo3(signature = (model_json, from_json, to_json_, kind, opts_json, contracts_json=None))]
346fn connect(
347    model_json: &str,
348    from_json: &str,
349    to_json_: &str,
350    kind: &str,
351    opts_json: &str,
352    contracts_json: Option<&str>,
353) -> PyResult<String> {
354    let model: Model = parse_json(model_json, "model")?;
355    let from: Endpoint = parse_json(from_json, "from endpoint")?;
356    let to: Endpoint = parse_json(to_json_, "to endpoint")?;
357    let opts: ConnectOptions = parse_json(opts_json, "connect options")?;
358    let contracts: ContractRegistry = match contracts_json {
359        Some(text) => parse_json(text, "contract registry")?,
360        None => ContractRegistry::new(),
361    };
362    let mut builder = ModelBuilder::from_model(model).with_contracts(contracts);
363    let wire_id = builder
364        .connect(from, to, kind, opts)
365        .map_err(builder_err_to_py)?
366        .to_string();
367    to_json(&ConnectResult {
368        model: builder.into_model(),
369        wire_id,
370    })
371}
372
373/// `bbox_map_json` is `{"<block_id>": [w, h], ...}` for each block in the model -- the caller is
374/// expected to have already evaluated each block's GSF v2 contract to get its bbox (this
375/// function does not itself know about contracts, matching `ModelBuilder::auto_arrange`'s
376/// decoupled `bbox_of` design). If a block id is missing from the map, `(0, 0)` is used as its
377/// size rather than raising. Returns the updated `Model` JSON with positions rewritten.
378#[pyfunction]
379fn auto_arrange(
380    model_json: &str,
381    bbox_map_json: &str,
382    column_gap: i64,
383    row_gap: i64,
384) -> PyResult<String> {
385    let model: Model = parse_json(model_json, "model")?;
386    let bbox_map: HashMap<String, (i64, i64)> = parse_json(bbox_map_json, "bbox map")?;
387    let mut builder = ModelBuilder::from_model(model);
388    builder.auto_arrange(
389        |b| bbox_map.get(&b.id).copied().unwrap_or((0, 0)),
390        column_gap,
391        row_gap,
392    );
393    to_json(&builder.into_model())
394}
395
396/// Parses `json` as a full `.gsim_sch` document (rejects a non-v2 `schema_version` with a clear
397/// message), and returns the canonical re-serialized JSON -- proving round-trip validity.
398#[pyfunction]
399fn load_document(json: &str) -> PyResult<String> {
400    let doc = GsimSchDocument::from_json(json).map_err(to_py_err)?;
401    to_json(&doc)
402}
403
404/// Wraps a `Model` JSON into a full `{"schema_version": 2, "model": ...}` document, pretty-
405/// printed.
406#[pyfunction]
407fn save_document(model_json: &str) -> PyResult<String> {
408    let model: Model = parse_json(model_json, "model")?;
409    GsimSchDocument::new(model)
410        .to_json_pretty()
411        .map_err(to_py_err)
412}
413
414/// `existing_json` is a JSON array of `{"x":.., "y":.., "w":.., "h":..}` rectangles; `axis` is
415/// `"horizontal"` or `"vertical"`. Returns `[x, y]` as a JSON array.
416#[pyfunction]
417#[allow(clippy::too_many_arguments)]
418fn place_without_overlap(
419    existing_json: &str,
420    w: i64,
421    h: i64,
422    desired_x: i64,
423    desired_y: i64,
424    axis: &str,
425    margin: i64,
426    grid: i64,
427) -> PyResult<String> {
428    let existing: Vec<Rect> = parse_json(existing_json, "existing rects")?;
429    let axis = match axis {
430        "horizontal" => Axis::Horizontal,
431        "vertical" => Axis::Vertical,
432        other => {
433            return Err(to_py_err(format!(
434                "invalid axis '{other}' (must be \"horizontal\" or \"vertical\")"
435            )))
436        }
437    };
438    let (x, y) = layout::place_without_overlap(
439        &existing,
440        (w, h),
441        (desired_x, desired_y),
442        axis,
443        margin,
444        grid,
445    );
446    to_json(&(x, y))
447}
448
449#[derive(Deserialize)]
450struct LayoutBlockSpec {
451    id: String,
452    w: i64,
453    h: i64,
454}
455
456/// `blocks_json` is `[{"id": "...", "w": .., "h": ..}, ...]`, `edges_json` is
457/// `[["from_id","to_id"], ...]`. Returns `{"<block_id>": [x, y], ...}`.
458#[pyfunction]
459fn layered_layout(
460    blocks_json: &str,
461    edges_json: &str,
462    column_gap: i64,
463    row_gap: i64,
464    grid: i64,
465) -> PyResult<String> {
466    let block_specs: Vec<LayoutBlockSpec> = parse_json(blocks_json, "blocks")?;
467    let edge_specs: Vec<(String, String)> = parse_json(edges_json, "edges")?;
468
469    let inputs: Vec<LayoutInput> = block_specs
470        .iter()
471        .map(|b| LayoutInput {
472            id: &b.id,
473            size: (b.w, b.h),
474        })
475        .collect();
476    let edges: Vec<(&str, &str)> = edge_specs
477        .iter()
478        .map(|(from, to)| (from.as_str(), to.as_str()))
479        .collect();
480
481    let positions = layout::layered_layout(&inputs, &edges, column_gap, row_gap, grid);
482    to_json(&positions)
483}
484
485#[pymodule]
486fn gsim_py(m: &Bound<'_, PyModule>) -> PyResult<()> {
487    m.add_function(wrap_pyfunction!(version, m)?)?;
488    m.add_function(wrap_pyfunction!(capabilities, m)?)?;
489    m.add_function(wrap_pyfunction!(catalog, m)?)?;
490    m.add_function(wrap_pyfunction!(evaluate_component, m)?)?;
491    m.add_function(wrap_pyfunction!(validate_parameters, m)?)?;
492    m.add_function(wrap_pyfunction!(new_model, m)?)?;
493    m.add_function(wrap_pyfunction!(add_block, m)?)?;
494    m.add_function(wrap_pyfunction!(compile, m)?)?;
495    m.add_function(wrap_pyfunction!(add_subckt_def, m)?)?;
496    m.add_function(wrap_pyfunction!(instantiate_subckt, m)?)?;
497    m.add_function(wrap_pyfunction!(remove_block, m)?)?;
498    m.add_function(wrap_pyfunction!(set_param, m)?)?;
499    m.add_function(wrap_pyfunction!(add_model_param, m)?)?;
500    m.add_function(wrap_pyfunction!(connect, m)?)?;
501    m.add_function(wrap_pyfunction!(auto_arrange, m)?)?;
502    m.add_function(wrap_pyfunction!(load_document, m)?)?;
503    m.add_function(wrap_pyfunction!(save_document, m)?)?;
504    m.add_function(wrap_pyfunction!(place_without_overlap, m)?)?;
505    m.add_function(wrap_pyfunction!(layered_layout, m)?)?;
506    Ok(())
507}
508
509#[cfg(test)]
510mod tests {
511    use super::*;
512
513    #[test]
514    fn full_flow_new_model_add_blocks_connect_auto_arrange_save_load_round_trips() {
515        let model = new_model("m1", "My Model", 10).unwrap();
516
517        let spec1 = r#"{"type":"signal.step","paradigm":"signal-flow","domain":"control","position":[0,0],"rotation":0,"id":"src1"}"#;
518        let add1: Value = serde_json::from_str(&add_block(&model, spec1).unwrap()).unwrap();
519        let model = add1["model"].to_string();
520        assert_eq!(add1["block_id"], "src1");
521
522        let spec2 = r#"{"type":"control.gain","paradigm":"signal-flow","domain":"control","position":[0,0],"rotation":0,"id":"gain1"}"#;
523        let add2: Value = serde_json::from_str(&add_block(&model, spec2).unwrap()).unwrap();
524        let model = add2["model"].to_string();
525        assert_eq!(add2["block_id"], "gain1");
526
527        let from = r#"{"block":"src1","port":"out"}"#;
528        let to = r#"{"block":"gain1","port":"in"}"#;
529        let conn: Value =
530            serde_json::from_str(&connect(&model, from, to, "signal", "{}", None).unwrap())
531                .unwrap();
532        let model = conn["model"].to_string();
533        assert_eq!(conn["wire_id"], "wire1");
534
535        let bbox_map = r#"{"src1": [40, 20], "gain1": [40, 20]}"#;
536        let model = auto_arrange(&model, bbox_map, 20, 10).unwrap();
537
538        let saved = save_document(&model).unwrap();
539        assert!(saved.contains("\"schema_version\": 2"));
540
541        let reloaded = load_document(&saved).unwrap();
542        let reloaded_val: Value = serde_json::from_str(&reloaded).unwrap();
543        assert_eq!(reloaded_val["model"]["id"], "m1");
544        assert_eq!(reloaded_val["model"]["blocks"].as_array().unwrap().len(), 2);
545        assert_eq!(reloaded_val["model"]["wires"].as_array().unwrap().len(), 1);
546
547        // auto_arrange actually moved src1 before gain1.
548        let model_val: Value = serde_json::from_str(&model).unwrap();
549        let blocks = model_val["blocks"].as_array().unwrap();
550        let src_x = blocks.iter().find(|b| b["id"] == "src1").unwrap()["position"][0]
551            .as_i64()
552            .unwrap();
553        let gain_x = blocks.iter().find(|b| b["id"] == "gain1").unwrap()["position"][0]
554            .as_i64()
555            .unwrap();
556        assert!(src_x < gain_x);
557    }
558
559    #[test]
560    fn remove_block_cascades_wire_removal() {
561        let model = new_model("m1", "M", 10).unwrap();
562        let spec1 = r#"{"type":"passive.resistor","paradigm":"physical-network","domain":"electrical","position":[0,0],"rotation":0,"id":"r1"}"#;
563        let add1: Value = serde_json::from_str(&add_block(&model, spec1).unwrap()).unwrap();
564        let model = add1["model"].to_string();
565        let spec2 = r#"{"type":"passive.capacitor","paradigm":"physical-network","domain":"electrical","position":[0,0],"rotation":0,"id":"c1"}"#;
566        let add2: Value = serde_json::from_str(&add_block(&model, spec2).unwrap()).unwrap();
567        let model = add2["model"].to_string();
568
569        let from = r#"{"block":"r1","port":"n"}"#;
570        let to = r#"{"block":"c1","port":"p"}"#;
571        let conn: Value = serde_json::from_str(
572            &connect(&model, from, to, "physical-electrical", "{}", None).unwrap(),
573        )
574        .unwrap();
575        let model = conn["model"].to_string();
576
577        let after_remove: Value =
578            serde_json::from_str(&remove_block(&model, "r1").unwrap()).unwrap();
579        assert_eq!(after_remove["blocks"].as_array().unwrap().len(), 1);
580        assert_eq!(after_remove["wires"].as_array().unwrap().len(), 0);
581    }
582
583    #[test]
584    fn set_param_and_add_model_param_round_trip() {
585        let model = new_model("m1", "M", 10).unwrap();
586        let spec = r#"{"type":"passive.resistor","paradigm":"physical-network","domain":"electrical","position":[0,0],"rotation":0,"id":"r1"}"#;
587        let add: Value = serde_json::from_str(&add_block(&model, spec).unwrap()).unwrap();
588        let model = add["model"].to_string();
589
590        let model = set_param(&model, "r1", "R", "1000").unwrap();
591        let model_val: Value = serde_json::from_str(&model).unwrap();
592        assert_eq!(model_val["blocks"][0]["params"]["R"], 1000);
593
594        let model = add_model_param(&model, "vcc", "5.0").unwrap();
595        let model_val: Value = serde_json::from_str(&model).unwrap();
596        assert_eq!(model_val["params"][0]["name"], "vcc");
597        assert_eq!(model_val["params"][0]["value"], 5.0);
598    }
599
600    #[test]
601    fn set_param_on_unknown_block_raises_with_real_message() {
602        let model = new_model("m1", "M", 10).unwrap();
603        let err = set_param(&model, "ghost", "R", "1000").unwrap_err();
604        Python::attach(|py| {
605            let msg = err.value(py).to_string();
606            assert!(msg.contains("no block with id 'ghost'"), "got: {msg}");
607        });
608    }
609
610    #[test]
611    fn connect_dangling_endpoint_raises_with_dangling_in_message() {
612        let model = new_model("m1", "M", 10).unwrap();
613        let spec = r#"{"type":"passive.resistor","paradigm":"physical-network","domain":"electrical","position":[0,0],"rotation":0,"id":"r1"}"#;
614        let add: Value = serde_json::from_str(&add_block(&model, spec).unwrap()).unwrap();
615        let model = add["model"].to_string();
616
617        let from = r#"{"block":"r1","port":"p"}"#;
618        let to = r#"{"block":"ghost","port":"p"}"#;
619        let err = connect(&model, from, to, "physical-electrical", "{}", None).unwrap_err();
620        Python::attach(|py| {
621            let msg = err.value(py).to_string();
622            assert!(
623                msg.to_lowercase().contains("unknown block")
624                    || msg.to_lowercase().contains("dangling")
625                    || msg.contains("ghost"),
626                "got: {msg}"
627            );
628        });
629    }
630
631    #[test]
632    fn connect_cross_paradigm_raises_with_cross_paradigm_in_message() {
633        let model = new_model("m1", "M", 10).unwrap();
634        let spec1 = r#"{"type":"passive.resistor","paradigm":"physical-network","domain":"electrical","position":[0,0],"rotation":0,"id":"r1"}"#;
635        let add1: Value = serde_json::from_str(&add_block(&model, spec1).unwrap()).unwrap();
636        let model = add1["model"].to_string();
637        let spec2 = r#"{"type":"control.gain","paradigm":"signal-flow","domain":"control","position":[0,0],"rotation":0,"id":"gain1"}"#;
638        let add2: Value = serde_json::from_str(&add_block(&model, spec2).unwrap()).unwrap();
639        let model = add2["model"].to_string();
640
641        let from = r#"{"block":"r1","port":"p"}"#;
642        let to = r#"{"block":"gain1","port":"in"}"#;
643        let err = connect(&model, from, to, "signal", "{}", None).unwrap_err();
644        Python::attach(|py| {
645            let msg = err.value(py).to_string();
646            // `BuilderError::CrossParadigm`'s `Display` names both paradigms and the reason
647            // rather than using the literal word "cross-paradigm" -- this asserts the specific
648            // variant's message (not a generic "connect failed"), matching what the task
649            // description means by "include ... literally".
650            assert!(
651                msg.contains(
652                    "cannot connect a PhysicalNetwork block directly to a SignalFlow block"
653                ),
654                "got: {msg}"
655            );
656        });
657    }
658
659    #[test]
660    fn connect_two_different_physical_domains_raises_port_kind_mismatch() {
661        let model = new_model("m1", "M", 10).unwrap();
662        let spec1 = r#"{"type":"passive.resistor","paradigm":"physical-network","domain":"electrical","position":[0,0],"rotation":0,"id":"r1"}"#;
663        let add1: Value = serde_json::from_str(&add_block(&model, spec1).unwrap()).unwrap();
664        let model = add1["model"].to_string();
665        let spec2 = r#"{"type":"thermal.resistance","paradigm":"physical-network","domain":"thermal","position":[0,0],"rotation":0,"id":"rth"}"#;
666        let add2: Value = serde_json::from_str(&add_block(&model, spec2).unwrap()).unwrap();
667        let model = add2["model"].to_string();
668
669        let from = r#"{"block":"r1","port":"p"}"#;
670        let to = r#"{"block":"rth","port":"a"}"#;
671        let err = connect(&model, from, to, "physical-electrical", "{}", None).unwrap_err();
672        Python::attach(|py| {
673            let msg = err.value(py).to_string();
674            // The stable keyword prefix, then the full underlying message naming both the port
675            // and the kind it actually declares -- the wrapper adds, never replaces.
676            assert!(msg.starts_with("port-kind-mismatch: "), "got: {msg}");
677            assert!(msg.contains("'rth.a' is declared 'thermal'"), "got: {msg}");
678            assert!(
679                msg.contains("as a 'physical-electrical' wire"),
680                "got: {msg}"
681            );
682        });
683    }
684
685    #[test]
686    fn connect_fanning_in_on_a_signal_port_raises_port_fan_in_on_signal() {
687        let mut model = new_model("m1", "M", 10).unwrap();
688        for id in ["s1", "s2", "g1"] {
689            let spec = format!(
690                r#"{{"type":"control.gain","paradigm":"signal-flow","domain":"control","position":[0,0],"rotation":0,"id":"{id}"}}"#
691            );
692            let add: Value = serde_json::from_str(&add_block(&model, &spec).unwrap()).unwrap();
693            model = add["model"].to_string();
694        }
695        let to = r#"{"block":"g1","port":"in"}"#;
696        let first: Value = serde_json::from_str(
697            &connect(
698                &model,
699                r#"{"block":"s1","port":"out"}"#,
700                to,
701                "signal",
702                "{}",
703                None,
704            )
705            .unwrap(),
706        )
707        .unwrap();
708        let model = first["model"].to_string();
709
710        let err = connect(
711            &model,
712            r#"{"block":"s2","port":"out"}"#,
713            to,
714            "signal",
715            "{}",
716            None,
717        )
718        .unwrap_err();
719        Python::attach(|py| {
720            let msg = err.value(py).to_string();
721            assert!(msg.starts_with("port-fan-in-on-signal: "), "got: {msg}");
722            assert!(
723                msg.contains("causal port 'g1.in' is already driven"),
724                "got: {msg}"
725            );
726        });
727    }
728
729    #[test]
730    fn connect_a_reserved_kind_raises_port_reserved_kind() {
731        let mut model = new_model("m1", "M", 10).unwrap();
732        for id in ["m1b", "m2b"] {
733            let spec = format!(
734                r#"{{"type":"magnetic.core","paradigm":"physical-network","domain":"mixed","position":[0,0],"rotation":0,"id":"{id}"}}"#
735            );
736            let add: Value = serde_json::from_str(&add_block(&model, &spec).unwrap()).unwrap();
737            model = add["model"].to_string();
738        }
739        let err = connect(
740            &model,
741            r#"{"block":"m1b","port":"p"}"#,
742            r#"{"block":"m2b","port":"p"}"#,
743            "reserved.physical-magnetic",
744            "{}",
745            None,
746        )
747        .unwrap_err();
748        Python::attach(|py| {
749            let msg = err.value(py).to_string();
750            assert!(msg.starts_with("port-reserved-kind: "), "got: {msg}");
751            assert!(msg.contains("reserved.physical-magnetic"), "got: {msg}");
752        });
753    }
754
755    /// A `{"<block type>": <contract>}` payload for `connect`'s optional sixth argument: one
756    /// gain whose port `dim` follows its own `width` parameter.
757    fn gain_registry_json() -> String {
758        r#"{"control.gain": {
759            "name": "control.gain",
760            "label": "Gain",
761            "parameters": [{"name": "width", "type": "number", "default": 1}],
762            "ports": [
763                {"id": "in", "side": "left", "kind": "signal", "direction": "in",
764                 "dim": ["${{ params.width }}"]},
765                {"id": "out", "side": "right", "kind": "signal", "direction": "out",
766                 "dim": ["${{ params.width }}"]}
767            ],
768            "geometry": {"bbox": [40, 30], "primitives": []}
769        }}"#
770        .to_string()
771    }
772
773    /// Two `control.gain` blocks of the given widths, wired `g1.out -> g2.in`, with the registry
774    /// above supplied (or not).
775    fn gain_chain(from_width: i64, to_width: i64, contracts: Option<&str>) -> PyResult<String> {
776        let mut model = new_model("m1", "M", 10).unwrap();
777        for (id, width) in [("g1", from_width), ("g2", to_width)] {
778            let spec = format!(
779                r#"{{"type":"control.gain","paradigm":"signal-flow","domain":"signal","position":[0,0],"rotation":0,"id":"{id}","params":{{"width":{width}}}}}"#
780            );
781            let add: Value = serde_json::from_str(&add_block(&model, &spec).unwrap()).unwrap();
782            model = add["model"].to_string();
783        }
784        connect(
785            &model,
786            r#"{"block":"g1","port":"out"}"#,
787            r#"{"block":"g2","port":"in"}"#,
788            "signal",
789            "{}",
790            contracts,
791        )
792    }
793
794    #[test]
795    fn connect_a_dim_mismatch_raises_port_dim_mismatch_only_when_contracts_are_supplied() {
796        let registry = gain_registry_json();
797
798        let err = gain_chain(3, 1, Some(&registry)).unwrap_err();
799        Python::attach(|py| {
800            let msg = err.value(py).to_string();
801            assert!(msg.starts_with("port-dim-mismatch: "), "got: {msg}");
802            assert!(
803                msg.contains("cannot connect 'g1.out' to 'g2.in'"),
804                "got: {msg}"
805            );
806            assert!(
807                msg.contains("the source produces dim [3], but the destination requires dim [1]"),
808                "got: {msg}"
809            );
810        });
811
812        // Same widths -> accepted, so this is not a checker that rejects everything.
813        gain_chain(3, 3, Some(&registry)).unwrap();
814
815        // And with no registry the mismatch is simply invisible, exactly as before: the document
816        // alone has no idea what dimension either port carries.
817        gain_chain(3, 1, None).unwrap();
818    }
819
820    #[test]
821    fn connect_a_signal_wire_onto_a_contract_declared_physical_port_raises_port_kind_mismatch() {
822        // Neither block-level check can see this: both blocks are `physical-network` with
823        // `domain: "mixed"`. Only the registered contract knows `sen2.p` is conserving.
824        let contracts = r#"{"sensor.voltage": {
825            "name": "sensor.voltage",
826            "label": "Voltage sensor",
827            "ports": [
828                {"id": "p", "side": "left", "kind": "physical-electrical", "direction": "inout"},
829                {"id": "out", "side": "right", "kind": "signal", "direction": "out"}
830            ],
831            "geometry": {"bbox": [40, 30], "primitives": []}
832        }}"#;
833
834        let mut model = new_model("m1", "M", 10).unwrap();
835        for id in ["sen", "sen2"] {
836            let spec = format!(
837                r#"{{"type":"sensor.voltage","paradigm":"physical-network","domain":"mixed","position":[0,0],"rotation":0,"id":"{id}"}}"#
838            );
839            let add: Value = serde_json::from_str(&add_block(&model, &spec).unwrap()).unwrap();
840            model = add["model"].to_string();
841        }
842        let from = r#"{"block":"sen","port":"out"}"#;
843        let to = r#"{"block":"sen2","port":"p"}"#;
844
845        let err = connect(&model, from, to, "signal", "{}", Some(contracts)).unwrap_err();
846        Python::attach(|py| {
847            let msg = err.value(py).to_string();
848            assert!(msg.starts_with("port-kind-mismatch: "), "got: {msg}");
849            assert!(
850                msg.contains("'sen2.p' is declared 'physical-electrical'"),
851                "got: {msg}"
852            );
853        });
854
855        // Without the contract this is still accepted -- the fallback is preserved, not tightened.
856        connect(&model, from, to, "signal", "{}", None).unwrap();
857    }
858
859    #[test]
860    fn connect_with_malformed_contracts_json_raises_value_error_not_panic() {
861        let err = gain_chain(1, 1, Some("not json")).unwrap_err();
862        Python::attach(|py| {
863            let msg = err.value(py).to_string();
864            assert!(msg.contains("invalid contract registry JSON"), "got: {msg}");
865        });
866    }
867
868    /// `gsim-tools` and any agent building a schematic in code reach this crate, not the Rust
869    /// API, so the rating slot has to survive *this* JSON contract too. A rating dropped here
870    /// would be a limit the author wrote and nothing enforces.
871    #[test]
872    fn add_block_carries_a_rating_and_compile_emits_it() {
873        let mut model = new_model("m1", "M", 10).unwrap();
874        for spec in [
875            r#"{"type":"source.voltage.dc","paradigm":"physical-network","domain":"electrical","position":[0,0],"rotation":0,"id":"Vin","params":{"V":10.0}}"#,
876            r#"{"type":"passive.inductor","paradigm":"physical-network","domain":"electrical","position":[0,0],"rotation":0,"id":"L1","params":{"L":3.6e-5},"ratings":{"i_max":60,"on_violation":"stop"}}"#,
877            r#"{"type":"routing.ground","paradigm":"physical-network","domain":"electrical","position":[0,0],"rotation":0,"id":"gnd"}"#,
878        ] {
879            let add: Value = serde_json::from_str(&add_block(&model, spec).unwrap()).unwrap();
880            model = add["model"].to_string();
881        }
882        let parsed: Value = serde_json::from_str(&model).unwrap();
883        let rated = parsed["blocks"]
884            .as_array()
885            .unwrap()
886            .iter()
887            .find(|b| b["id"] == "L1")
888            .unwrap();
889        assert_eq!(rated["ratings"]["i_max"], 60);
890
891        for (from, to) in [
892            (
893                r#"{"block":"Vin","port":"p"}"#,
894                r#"{"block":"L1","port":"p"}"#,
895            ),
896            (
897                r#"{"block":"L1","port":"n"}"#,
898                r#"{"block":"gnd","port":"p"}"#,
899            ),
900            (
901                r#"{"block":"Vin","port":"n"}"#,
902                r#"{"block":"gnd","port":"p"}"#,
903            ),
904        ] {
905            let conn: Value = serde_json::from_str(
906                &connect(&model, from, to, "physical-electrical", "{}", None).unwrap(),
907            )
908            .unwrap();
909            model = conn["model"].to_string();
910        }
911
912        let out = compile(&model, "general-simulator").unwrap();
913        let netlist: Value = serde_json::from_str(&out).unwrap();
914        let netlist = netlist["netlist"].as_str().unwrap();
915        assert!(netlist.contains("i_max=60 on_violation=stop"), "{netlist}");
916    }
917
918    #[test]
919    fn add_block_duplicate_id_raises_with_duplicate_in_message() {
920        let model = new_model("m1", "M", 10).unwrap();
921        let spec = r#"{"type":"passive.resistor","paradigm":"physical-network","domain":"electrical","position":[0,0],"rotation":0,"id":"r1"}"#;
922        let add: Value = serde_json::from_str(&add_block(&model, spec).unwrap()).unwrap();
923        let model = add["model"].to_string();
924
925        let err = add_block(&model, spec).unwrap_err();
926        Python::attach(|py| {
927            let msg = err.value(py).to_string();
928            assert!(msg.to_lowercase().contains("duplicate"), "got: {msg}");
929        });
930    }
931
932    #[test]
933    fn add_block_invalid_rotation_raises() {
934        let model = new_model("m1", "M", 10).unwrap();
935        let spec = r#"{"type":"passive.resistor","paradigm":"physical-network","domain":"electrical","position":[0,0],"rotation":45,"id":"r1"}"#;
936        let err = add_block(&model, spec).unwrap_err();
937        Python::attach(|py| {
938            let msg = err.value(py).to_string();
939            assert!(msg.to_lowercase().contains("rotation"), "got: {msg}");
940        });
941    }
942
943    #[test]
944    fn bad_json_raises_value_error_not_panic() {
945        let result = add_block(r#"{not json"#, "{}");
946        assert!(result.is_err());
947    }
948
949    #[test]
950    fn evaluate_component_and_validate_parameters_on_a_real_contract() {
951        let contract_json = std::fs::read_to_string(concat!(
952            env!("CARGO_MANIFEST_DIR"),
953            "/../gsim-core/tests/fixtures/general_simulator/control.sum.json"
954        ))
955        .unwrap();
956
957        let evaluated = evaluate_component(&contract_json, r#"{"signs": [1, 1, -1]}"#).unwrap();
958        let evaluated_val: Value = serde_json::from_str(&evaluated).unwrap();
959        assert_eq!(evaluated_val["ports"].as_array().unwrap().len(), 4); // 3 inputs + out
960
961        let failures = validate_parameters(&contract_json, r#"{"signs": []}"#).unwrap();
962        let failures_val: Value = serde_json::from_str(&failures).unwrap();
963        assert_eq!(failures_val.as_array().unwrap().len(), 1);
964        assert_eq!(failures_val[0]["parameter"], "signs");
965
966        let ok = validate_parameters(&contract_json, r#"{"signs": [1, -1]}"#).unwrap();
967        assert_eq!(ok, "[]");
968    }
969
970    #[test]
971    fn evaluate_component_bad_contract_json_raises() {
972        let err = evaluate_component("{not json", "{}").unwrap_err();
973        Python::attach(|py| {
974            let msg = err.value(py).to_string();
975            assert!(!msg.is_empty());
976        });
977    }
978
979    #[test]
980    fn place_without_overlap_steps_around_a_blocker() {
981        let existing = r#"[{"x":100,"y":100,"w":20,"h":20}]"#;
982        let result =
983            place_without_overlap(existing, 20, 20, 100, 100, "horizontal", 5, 10).unwrap();
984        let pos: (i64, i64) = serde_json::from_str(&result).unwrap();
985        assert_ne!(pos, (100, 100));
986    }
987
988    #[test]
989    fn place_without_overlap_invalid_axis_raises() {
990        let err = place_without_overlap("[]", 20, 20, 0, 0, "diagonal", 5, 10).unwrap_err();
991        Python::attach(|py| {
992            let msg = err.value(py).to_string();
993            assert!(msg.contains("axis"), "got: {msg}");
994        });
995    }
996
997    #[test]
998    fn layered_layout_orders_a_chain_left_to_right() {
999        let blocks =
1000            r#"[{"id":"a","w":40,"h":20},{"id":"b","w":40,"h":20},{"id":"c","w":40,"h":20}]"#;
1001        let edges = r#"[["a","b"],["b","c"]]"#;
1002        let result = layered_layout(blocks, edges, 20, 10, 10).unwrap();
1003        let positions: HashMap<String, (i64, i64)> = serde_json::from_str(&result).unwrap();
1004        assert!(positions["a"].0 < positions["b"].0);
1005        assert!(positions["b"].0 < positions["c"].0);
1006    }
1007
1008    #[test]
1009    fn load_document_rejects_non_v2_schema_version() {
1010        let text = r#"{"schema_version":1,"model":{"id":"m","name":"M","blocks":[],"wires":[]}}"#;
1011        let err = load_document(text).unwrap_err();
1012        Python::attach(|py| {
1013            let msg = err.value(py).to_string();
1014            assert!(
1015                msg.contains("schema_version") || msg.contains("2"),
1016                "got: {msg}"
1017            );
1018        });
1019    }
1020
1021    #[test]
1022    fn version_is_not_empty() {
1023        assert!(!version().is_empty());
1024    }
1025
1026    // -- subckt ------------------------------------------------------------
1027
1028    const LEAF_DEF: &str = r#"{"id":"leaf","name":"LEAF","ports":[
1029        {"id":"a","kind":"physical-electrical"},
1030        {"id":"b","kind":"physical-electrical"}]}"#;
1031
1032    fn err_msg(err: PyErr) -> String {
1033        Python::attach(|py| err.value(py).to_string())
1034    }
1035
1036    #[test]
1037    fn add_subckt_def_then_instantiate_twice_and_wire_both() {
1038        let model = new_model("m1", "M", 10).unwrap();
1039        let added: Value =
1040            serde_json::from_str(&add_subckt_def(&model, LEAF_DEF).unwrap()).unwrap();
1041        assert_eq!(added["def_id"], "leaf");
1042        let model = serde_json::to_string(&added["model"]).unwrap();
1043
1044        let mut model = model;
1045        for id in ["x1", "x2"] {
1046            let spec = format!(r#"{{"def_ref":"leaf","position":[0,0],"id":"{id}"}}"#);
1047            let r: Value =
1048                serde_json::from_str(&instantiate_subckt(&model, &spec).unwrap()).unwrap();
1049            assert_eq!(r["block_id"], id);
1050            model = serde_json::to_string(&r["model"]).unwrap();
1051        }
1052
1053        // Ordinary connect() wires the def's own port ids -- no catalogue lookup involved.
1054        let r: Value = serde_json::from_str(
1055            &connect(
1056                &model,
1057                r#"{"block":"x1","port":"b"}"#,
1058                r#"{"block":"x2","port":"a"}"#,
1059                "physical-electrical",
1060                "{}",
1061                None,
1062            )
1063            .unwrap(),
1064        )
1065        .unwrap();
1066        let model = serde_json::to_string(&r["model"]).unwrap();
1067
1068        let doc = save_document(&model).unwrap();
1069        let reloaded: Value = serde_json::from_str(&load_document(&doc).unwrap()).unwrap();
1070        assert_eq!(reloaded["schema_version"], 2);
1071        assert_eq!(
1072            reloaded["model"]["subckt_defs"].as_array().unwrap().len(),
1073            1
1074        );
1075        assert_eq!(reloaded["model"]["blocks"].as_array().unwrap().len(), 2);
1076        assert_eq!(reloaded["model"]["blocks"][0]["subckt_ref"], "leaf");
1077        assert_eq!(reloaded["model"]["blocks"][0]["paradigm"], "spice-subckt");
1078        assert_eq!(
1079            reloaded["model"]["blocks"][0]["type"],
1080            "spice-subckt.instance"
1081        );
1082    }
1083
1084    #[test]
1085    fn add_subckt_def_duplicate_id_raises_with_duplicate_in_message() {
1086        let model = new_model("m1", "M", 10).unwrap();
1087        let added: Value =
1088            serde_json::from_str(&add_subckt_def(&model, LEAF_DEF).unwrap()).unwrap();
1089        let model = serde_json::to_string(&added["model"]).unwrap();
1090        let msg = err_msg(add_subckt_def(&model, LEAF_DEF).unwrap_err());
1091        assert!(msg.starts_with("duplicate:"), "got: {msg}");
1092    }
1093
1094    #[test]
1095    fn add_subckt_def_cycle_raises_naming_the_actual_cycle() {
1096        let model = new_model("m1", "M", 10).unwrap();
1097        let a = r#"{"id":"a","name":"A","instances":[{"id":"X1","def_ref":"b"}]}"#;
1098        let added: Value = serde_json::from_str(&add_subckt_def(&model, a).unwrap()).unwrap();
1099        let model = serde_json::to_string(&added["model"]).unwrap();
1100        let b = r#"{"id":"b","name":"B","instances":[{"id":"X1","def_ref":"a"}]}"#;
1101        let msg = err_msg(add_subckt_def(&model, b).unwrap_err());
1102        assert!(msg.starts_with("cyclic-subckt-def:"), "got: {msg}");
1103        assert!(
1104            msg.contains("a -> b -> a") || msg.contains("b -> a -> b"),
1105            "the message must name the actual cycle, got: {msg}"
1106        );
1107    }
1108
1109    #[test]
1110    fn add_subckt_def_self_reference_raises() {
1111        let model = new_model("m1", "M", 10).unwrap();
1112        let d = r#"{"id":"loopy","name":"L","instances":[{"id":"X1","def_ref":"loopy"}]}"#;
1113        let msg = err_msg(add_subckt_def(&model, d).unwrap_err());
1114        assert!(msg.contains("loopy -> loopy"), "got: {msg}");
1115    }
1116
1117    #[test]
1118    fn add_subckt_def_bad_port_kind_raises() {
1119        let model = new_model("m1", "M", 10).unwrap();
1120        let d = r#"{"id":"d1","name":"D","ports":[{"id":"bus","kind":"physical-signal"}]}"#;
1121        let msg = err_msg(add_subckt_def(&model, d).unwrap_err());
1122        assert!(msg.starts_with("invalid-subckt:"), "got: {msg}");
1123        assert!(msg.contains("physical-signal"), "got: {msg}");
1124    }
1125
1126    #[test]
1127    fn instantiate_unknown_def_ref_raises() {
1128        let model = new_model("m1", "M", 10).unwrap();
1129        let msg = err_msg(
1130            instantiate_subckt(&model, r#"{"def_ref":"ghost","position":[0,0]}"#).unwrap_err(),
1131        );
1132        assert!(msg.starts_with("unknown-subckt-def:"), "got: {msg}");
1133        assert!(msg.contains("ghost"), "got: {msg}");
1134    }
1135
1136    #[test]
1137    fn instantiate_subckt_bad_json_raises_value_error_not_panic() {
1138        let model = new_model("m1", "M", 10).unwrap();
1139        assert!(instantiate_subckt(&model, "{not json").is_err());
1140        assert!(add_subckt_def(&model, "{not json").is_err());
1141    }
1142
1143    #[test]
1144    fn compile_emits_a_netlist_and_reports_notes() {
1145        let model = new_model("m1", "M", 10).unwrap();
1146        let r = |m: &str, s: &str| -> String {
1147            let v: Value = serde_json::from_str(&add_block(m, s).unwrap()).unwrap();
1148            serde_json::to_string(&v["model"]).unwrap()
1149        };
1150        let model = r(
1151            &model,
1152            r#"{"type":"passive.resistor","paradigm":"physical-network","domain":"electrical","position":[0,0],"rotation":0,"id":"R1","params":{"R":1000}}"#,
1153        );
1154        let model = r(
1155            &model,
1156            r#"{"type":"routing.ground","paradigm":"physical-network","domain":"electrical","position":[0,0],"rotation":0,"id":"gnd"}"#,
1157        );
1158        let mut model = model;
1159        for port in ["p", "n"] {
1160            let v: Value = serde_json::from_str(
1161                &connect(
1162                    &model,
1163                    &format!(r#"{{"block":"R1","port":"{port}"}}"#),
1164                    r#"{"block":"gnd","port":"p"}"#,
1165                    "physical-electrical",
1166                    "{}",
1167                    None,
1168                )
1169                .unwrap(),
1170            )
1171            .unwrap();
1172            model = serde_json::to_string(&v["model"]).unwrap();
1173        }
1174        let out: Value =
1175            serde_json::from_str(&compile(&model, "general-simulator").unwrap()).unwrap();
1176        assert!(
1177            out["netlist"].as_str().unwrap().contains("R1 0 0 1000"),
1178            "{out}"
1179        );
1180        assert!(out["notes"].is_array());
1181    }
1182
1183    #[test]
1184    fn compile_unknown_target_raises_keyword_prefixed() {
1185        let model = new_model("m1", "M", 10).unwrap();
1186        let msg = err_msg(compile(&model, "ngspice").unwrap_err());
1187        assert!(msg.starts_with("unknown-target:"), "got: {msg}");
1188    }
1189
1190    #[test]
1191    fn compile_unknown_type_raises_keyword_prefixed() {
1192        let model = new_model("m1", "M", 10).unwrap();
1193        let v: Value = serde_json::from_str(
1194            &add_block(
1195                &model,
1196                r#"{"type":"made.up.type","paradigm":"physical-network","domain":"electrical","position":[0,0],"rotation":0,"id":"z1"}"#,
1197            )
1198            .unwrap(),
1199        )
1200        .unwrap();
1201        let model = serde_json::to_string(&v["model"]).unwrap();
1202        let msg = err_msg(compile(&model, "general-simulator").unwrap_err());
1203        assert!(msg.starts_with("unknown-type:"), "got: {msg}");
1204        assert!(msg.contains("made.up.type"), "got: {msg}");
1205    }
1206}