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