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