use super::circuit_checks::declare_circuit_checks;
use super::element::{attributes, elements, rust_name};
use super::ir::{channels, fnv1a, slug, wire, Scope};
use super::part_fields::{part_field_forms, FIELD_ARGUMENTS};
pub use super::part_fields::{part_fields, FACET_FIELDS, PART_FIELDS};
use super::source::meta;
use super::{Declared, Family};
pub use super::{fragment, json, El, Json, Value};
use std::collections::HashMap;
elements! {
group(name): children;
resistor(name): leaf;
capacitor(name): leaf;
inductor(name): leaf;
voltagesource(name): leaf;
currentsource(name): leaf;
ground(name): leaf;
junction(name): leaf;
trace(from, to): leaf;
netlabel(net, connection): leaf;
part(name): leaf;
unit(part, unit): leaf;
code(name): leaf;
net(name): leaf;
attachment(name): leaf;
check: leaf;
accept: leaf;
}
attributes! {
pub trait SchematicAttrs {
resistance;
capacitance;
inductance;
voltage;
current;
excitation;
sch_x;
sch_y;
sch_rotation;
sch_mirror;
sch_style;
symbol;
library;
value;
source;
inputs;
suppressed;
pins;
spice;
no_connect;
reference;
part_number;
manufacturer;
mpn;
rating;
draw;
pinout_verified;
footprint_verified;
package_dimensions;
attrs;
suppliers;
alternates;
need;
datasheet;
lifecycle;
compliance;
shipping;
path;
role;
file;
mime;
id;
kind;
severity;
options;
check;
rule;
refs;
net;
region;
reason;
}
}
pub(crate) const FAMILY: Family = Family { module: "schematic", roots: &["group"], declare };
pub const SCH_WIRE: &str = "sch.wire";
pub const SCH_JUNCTION: &str = "sch.junction";
pub const SCH_LABEL: &str = "sch.label";
pub const NET: &str = "eda.net";
pub const ATTACHMENT: &str = "eda.source";
const ROLES: &[&str] = &["schematic", "project", "library", "other"];
const PART_PORT: &str = "part";
const PART_BODY_PORT: &str = "@part";
const VERTEX_PORT: &str = "v";
const PLACE: &[&str] = &["schX", "schY", "schRotation", "schMirror", "schStyle"];
pub const LIBRARY_PIN_PORT: &str = "pin:";
const CODE_OP: &str = "code";
pub fn sch_symbol_type_for(sockets: &[&str]) -> String {
format!("sch.symbol.{}", fnv1a(&sockets.join("\u{0}")))
}
fn is_js_space(c: char) -> bool {
matches!(c, '\t' | '\n' | '\u{b}' | '\u{c}' | '\r' | ' ' | '\u{a0}' | '\u{1680}' | '\u{2000}'..='\u{200a}' | '\u{2028}' | '\u{2029}' | '\u{202f}' | '\u{205f}' | '\u{3000}' | '\u{feff}')
}
fn pin_label(number: &str, name: Option<&str>) -> String {
let t = name.unwrap_or("").trim_matches(is_js_space);
if t.is_empty() || t == number || t == "~" {
number.to_string()
} else {
format!("{number} {t}")
}
}
pub fn part_type_for(pins: &[(String, String, Option<String>)]) -> String {
let signature: Vec<String> = pins.iter().map(|(id, number, name)| format!("{id}\u{0}{}", pin_label(number, name.as_deref()))).collect();
format!("eda.part.{}", fnv1a(&signature.join("\u{1}")))
}
struct Ideal {
symbol: &'static str,
value: Option<&'static str>,
pins: usize,
aliases: &'static [(&'static str, &'static str)],
power: Option<&'static str>,
excitation: bool,
}
const TWO: &[(&str, &str)] = &[("pin1", "1"), ("pin2", "2"), ("left", "1"), ("right", "2")];
const SOURCE: &[(&str, &str)] = &[("pin1", "1"), ("pin2", "2"), ("left", "1"), ("right", "2"), ("pos", "1"), ("neg", "2"), ("+", "1"), ("-", "2")];
fn ideal(tag: &str) -> Option<Ideal> {
let two = |symbol, value| Ideal { symbol, value: Some(value), pins: 2, aliases: TWO, power: None, excitation: false };
let source = |symbol, value| Ideal { symbol, value: Some(value), pins: 2, aliases: SOURCE, power: None, excitation: true };
Some(match tag {
"resistor" => two("Ideal:R", "resistance"),
"capacitor" => two("Ideal:C", "capacitance"),
"inductor" => two("Ideal:L", "inductance"),
"voltagesource" => source("Ideal:V", "voltage"),
"currentsource" => source("Ideal:I", "current"),
"ground" => Ideal { symbol: "Ideal:GND", value: None, pins: 1, aliases: &[("pin1", "1"), ("gnd", "1")], power: Some("GND"), excitation: false },
_ => return None,
})
}
fn declare(root: El) -> Result<Declared, String> {
refuse_unknown(&root, &["name"])?;
let name = match root.attr_of("name") {
Some(Json::Str(n)) if !n.is_empty() => n.clone(),
_ => return Err("group() needs a name".into()),
};
let mut s = Scope::new(&format!("eda:{}", slug(&name)), Json::obj().with("domain", "eda").with("rung", "board").with("name", name.as_str()));
let children = declare_circuit_checks(&mut s.meta, root.child_elements().collect())?;
declare_sheet(&mut s, &children)?;
Ok(Declared::Graph(s.build()))
}
struct Placed {
reference: String,
id: String,
units: Vec<(u32, String)>,
ideal: Option<(usize, &'static [(&'static str, &'static str)])>,
pins: Option<Vec<(String, String)>>,
}
fn refuse_unknown(el: &El, allowed: &[&str]) -> Result<(), String> {
match el.attrs.iter().find(|(k, _)| !allowed.contains(&k.as_str())) {
Some((k, _)) => Err(format!("{}: {} is not read on a schematic", el.call_text(), rust_name(k))),
None => Ok(()),
}
}
fn num(el: &El, prop: &str) -> Result<Option<f64>, String> {
match el.attr_of(prop) {
None => Ok(None),
Some(Json::Num(n)) => Ok(Some(*n)),
Some(other) => Err(format!("{}: {} is a number (mm or degrees), not {}", el.call_text(), rust_name(prop), other.text())),
}
}
fn text(el: &El, prop: &str, what: &str) -> Result<String, String> {
match el.attr_of(prop).and_then(Json::as_str) {
Some(v) if !v.trim().is_empty() => Ok(v.to_string()),
_ => Err(format!("{}: {} is {what}", el.call_text(), rust_name(prop))),
}
}
fn value_of(el: &El, prop: &str, example: &str) -> Result<Option<String>, String> {
match el.attr_of(prop) {
None => Ok(None),
Some(Json::Str(s)) => Ok(Some(s.clone())),
Some(n @ Json::Num(_)) => Ok(Some(n.text())),
Some(other) => Err(format!("{}: {} is a value ({example}), not {}", el.call_text(), rust_name(prop), other.text())),
}
}
fn spice_of(el: &El) -> Result<Option<Json>, String> {
let Some(v) = el.attr_of("spice") else { return Ok(None) };
let ok = match v {
Json::Arr(list) => list.iter().all(|b| {
b.get("id").and_then(Json::as_str).is_some()
&& b.get("model").and_then(Json::as_str).is_some()
&& matches!(b.get("terminals"), Some(Json::Obj(t)) if t.iter().all(|(_, n)| n.as_str().is_some()))
}),
_ => false,
};
if !ok {
return Err(format!("{}: spice is a list of {{ id, model, terminals: {{ formal: \"pin number\" }} }}", el.call_text()));
}
Ok(Some(v.clone()))
}
fn kicad_reference_of(el: &El, name: &str) -> Result<Option<Json>, String> {
match el.attr_of("reference") {
None => Ok(None),
Some(Json::Str(r)) if r.is_empty() => Err(format!("{}: reference is KiCad's reference designator (\"R1\")", el.call_text())),
Some(Json::Str(r)) if r == name => Err(format!("{}: reference is said only when it is not the name", el.call_text())),
Some(Json::Str(r)) => Ok(Some(Json::from(r.as_str()))),
Some(_) => Err(format!("{}: reference is KiCad's reference designator (\"R1\")", el.call_text())),
}
}
fn no_connect_of(el: &El) -> Result<Option<Json>, String> {
let Some(v) = el.attr_of("noConnect") else { return Ok(None) };
let ok = match v {
Json::Arr(list) => {
let numbers: Vec<&str> = list.iter().filter_map(Json::as_str).filter(|n| !n.is_empty()).collect();
!list.is_empty() && numbers.len() == list.len() && numbers.iter().enumerate().all(|(i, n)| !numbers[..i].contains(n))
}
_ => false,
};
if !ok {
return Err(format!("{}: noConnect is a list of pin numbers ([\"3\", \"4\"]), each once", el.call_text()));
}
Ok(Some(v.clone()))
}
const FIELD_PROPS: &[&str] = FIELD_ARGUMENTS;
fn fields_of(el: &El) -> Result<Option<Json>, String> {
let forms = part_field_forms(&el.call_text(), el)?;
Ok(if forms.is_empty() { None } else { Some(Json::Arr(forms)) })
}
fn place(s: &mut Scope, part: &mut Placed, unit: u32, el: &El, sockets: &[&str]) -> Result<(), String> {
let (x, y, rot) = (num(el, "schX")?, num(el, "schY")?, num(el, "schRotation")?);
let mirror = el.attr_of("schMirror");
let style = el.attr_of("schStyle");
if x.is_none() && y.is_none() {
let unplaced = if rot.is_some() {
Some("sch_rotation")
} else if mirror.is_some() {
Some("sch_mirror")
} else if style.is_some() {
Some("sch_style")
} else {
None
};
if let Some(what) = unplaced {
return Err(format!("{}: {what} needs sch_x and sch_y", el.call_text()));
}
if el.tag == "unit" {
return Err(format!("{}: a unit is placed: give it sch_x and sch_y", el.call_text()));
}
return Ok(());
}
if let Some(r) = rot {
if ![0.0, 90.0, 180.0, 270.0].contains(&r) {
return Err(format!("{}: sch_rotation is 0, 90, 180 or 270", el.call_text()));
}
}
let mirror = match mirror {
None => String::new(),
Some(Json::Str(m)) if m == "x" || m == "y" => m.clone(),
Some(_) => return Err(format!("{}: sch_mirror is \"x\" or \"y\"", el.call_text())),
};
let style = match style {
None => 1.0,
Some(Json::Num(n)) if n.fract() == 0.0 && *n >= 1.0 => *n,
Some(_) => return Err(format!("{}: sch_style is 1 or more (KiCad's De Morgan body style)", el.call_text())),
};
let inputs = vec![
("unit".to_string(), Json::Num(unit as f64)),
("style".into(), Json::Num(style)),
("at".into(), Json::obj().with("x", x.unwrap_or(0.0)).with("y", y.unwrap_or(0.0))),
("rot".into(), Json::Num(rot.unwrap_or(0.0))),
("mirror".into(), Json::from(mirror)),
(PART_PORT.into(), wire(&part.id, PART_BODY_PORT)),
];
let reference = part.reference.clone();
let id = s.add(&sch_symbol_type_for(sockets), inputs, Some(&format!("sym_{reference}_{unit}")), Some(&reference), meta(el))?;
part.units.push((unit, id));
Ok(())
}
fn pins_json(pins: &[(String, String, Option<String>)]) -> Json {
Json::Arr(
pins.iter()
.map(|(id, n, name)| {
let p = Json::obj().with("id", id.as_str()).with("number", n.as_str());
match name {
Some(name) => p.with("name", name.as_str()),
None => p,
}
})
.collect(),
)
}
fn declare_sheet(s: &mut Scope, children: &[&El]) -> Result<(), String> {
let mut parts: HashMap<String, Placed> = HashMap::new();
let mut junctions: HashMap<String, String> = HashMap::new();
let mut later: Vec<&El> = Vec::new();
for &el in children {
if let Some(ideal) = ideal(el.tag) {
let mut allowed = [&["name", "reference", "spice", "noConnect"], PLACE].concat();
allowed.extend(ideal.value);
if ideal.excitation {
allowed.push("excitation");
}
if ideal.power.is_none() {
allowed.extend(FIELD_PROPS);
}
refuse_unknown(el, &allowed)?;
let reference = match el.attr_of("name") {
Some(Json::Str(n)) if !n.is_empty() => n.clone(),
_ => return Err(format!("{}() needs a name", el.tag)),
};
if ideal.power.is_some() && !reference.starts_with('#') {
return Err(format!("{}: a ground symbol's name starts with # (#PWR1), as KiCad names power symbols", el.call_text()));
}
if parts.contains_key(&reference) {
return Err(format!("two parts are called {reference}"));
}
let pins: Vec<(String, String)> = (1..=ideal.pins).map(|i| (format!("p{i}"), i.to_string())).collect();
let raw = match ideal.value {
Some(v) => value_of(el, v, "\"1k\", 1000")?,
None => None,
};
let value = ideal.power.map(str::to_string).or(raw);
let mut inputs = vec![("ref".to_string(), Json::from(reference.as_str()))];
if let Some(kicad) = kicad_reference_of(el, &reference)? {
inputs.push(("reference".into(), kicad));
}
if let Some(value) = value {
inputs.push(("value".into(), value.into()));
}
inputs.push(("symbol".into(), ideal.symbol.into()));
let listed: Vec<(String, String, Option<String>)> = pins.iter().map(|(i, n)| (i.clone(), n.clone(), None)).collect();
inputs.push(("pins".into(), pins_json(&listed)));
inputs.push(("units".into(), Json::Num(1.0)));
if ideal.power.is_some() {
inputs.push(("powerSymbol".into(), true.into()));
}
if let Some(excitation) = el.attr_of("excitation") {
inputs.push(("excitation".into(), excitation.clone()));
}
if let Some(spice) = spice_of(el)? {
inputs.push(("spice".into(), spice));
}
if let Some(open) = no_connect_of(el)? {
inputs.push(("noConnect".into(), open));
}
if let Some(fields) = fields_of(el)? {
inputs.push(("foreign".into(), fields));
}
let part = s.add(&part_type_for(&listed), inputs, Some(&reference), Some(&reference), meta(el))?;
let mut placed = Placed { reference: reference.clone(), id: part, units: Vec::new(), ideal: Some((ideal.pins, ideal.aliases)), pins: None };
let sockets: Vec<&str> = pins.iter().map(|(id, _)| id.as_str()).collect();
place(s, &mut placed, 1, el, &sockets)?;
parts.insert(reference, placed);
continue;
}
match el.tag {
"part" => {
refuse_unknown(el, &[&["name", "reference", "symbol", "library", "value", "pins", "spice", "noConnect"], FIELD_PROPS, PLACE].concat())?;
let reference = text(el, "name", "the part's reference (U1)")?;
if parts.contains_key(&reference) {
return Err(format!("two parts are called {reference}"));
}
if el.attr_of("pins").is_some() {
let placed = netlist_part(s, el, &reference)?;
parts.insert(reference, placed);
continue;
}
let symbol = text(el, "symbol", "its library ref (\"Device:R_Small\")")?;
let mut halves = symbol.split(':');
if !(halves.next().is_some_and(|l| !l.is_empty()) && halves.next().is_some_and(|n| !n.is_empty()) && halves.next().is_none()) {
return Err(format!("{}: symbol is a library ref, \"Library:Symbol\" (\"Device:R_Small\"), not {symbol:?}", el.call_text()));
}
let library = text(el, "library", "the path of the .kicad_sym that holds the symbol")?;
if !library.to_lowercase().ends_with(".kicad_sym") {
return Err(format!("{}: library names a .kicad_sym file, not {library:?}", el.call_text()));
}
let value = value_of(el, "value", "\"LM358\", 1000")?;
let mut inputs = vec![("ref".to_string(), Json::from(reference.as_str()))];
if let Some(kicad) = kicad_reference_of(el, &reference)? {
inputs.push(("reference".into(), kicad));
}
if let Some(v) = value {
inputs.push(("value".into(), v.into()));
}
inputs.push(("symbol".into(), symbol.as_str().into()));
inputs.push(("library".into(), library.as_str().into()));
inputs.push(("pins".into(), Json::Arr(Vec::new())));
if let Some(spice) = spice_of(el)? {
inputs.push(("spice".into(), spice));
}
if let Some(open) = no_connect_of(el)? {
inputs.push(("noConnect".into(), open));
}
if let Some(fields) = fields_of(el)? {
inputs.push(("foreign".into(), fields));
}
let part = s.add(&part_type_for(&[]), inputs, Some(&reference), Some(&reference), meta(el))?;
let mut placed = Placed { reference: reference.clone(), id: part, units: Vec::new(), ideal: None, pins: None };
place(s, &mut placed, 1, el, &[])?;
parts.insert(reference, placed);
}
"code" => {
refuse_unknown(el, &["name", "source", "inputs", "suppressed"])?;
let name = text(el, "name", "the code part's id")?;
let suppressed = match el.attr_of("suppressed") {
None | Some(Json::Bool(false)) => false,
Some(Json::Bool(true)) => true,
Some(_) => return Err(format!("{}: suppressed is true or false", el.call_text())),
};
let source = text(el, "source", "the path of the file it runs, relative to this one")?;
let mut inputs = vec![("source".to_string(), Json::from(source.as_str()))];
match el.attr_of("inputs") {
None => {}
Some(Json::Obj(entries)) => {
if entries.iter().any(|(k, _)| k == "source") {
return Err(format!("{}: source is the file, not one of its inputs", el.call_text()));
}
inputs.extend(entries.iter().cloned());
}
Some(_) => return Err(format!("{}: inputs is an object of the file's parameters", el.call_text())),
}
if s.has(&slug(&name)) {
return Err(format!("two nodes are called {name}"));
}
let label = source.rsplit('/').next().unwrap_or(&source).to_string();
let code = s.add(CODE_OP, inputs, Some(&name), Some(&label), meta(el))?;
if suppressed {
s.disable(&code);
}
}
"junction" => {
refuse_unknown(el, &["name", "schX", "schY"])?;
let name = match el.attr_of("name") {
Some(Json::Str(n)) if !n.is_empty() => n.clone(),
_ => return Err("junction() needs a name".into()),
};
if junctions.contains_key(&name) {
return Err(format!("two junctions are called {name}"));
}
let at = Json::obj().with("x", num(el, "schX")?.unwrap_or(0.0)).with("y", num(el, "schY")?.unwrap_or(0.0));
let id = s.add(SCH_JUNCTION, vec![("at".into(), at)], Some(&name), Some("Junction"), meta(el))?;
junctions.insert(name, id);
}
"unit" | "trace" | "netlabel" | "net" | "attachment" => later.push(el),
_ => return Err(format!("{} is not read on a schematic (see commandagi::design::schematic)", el.call_text())),
}
}
for el in later.iter().filter(|el| el.tag == "unit") {
refuse_unknown(el, &[&["part", "unit"], PLACE].concat())?;
let reference = text(el, "part", "the reference of the part whose unit it places")?;
let part = parts.get_mut(&reference).ok_or_else(|| format!("{}: there is no part {reference}", el.call_text()))?;
let n = match el.attr_of("unit") {
Some(Json::Num(n)) if n.fract() == 0.0 && *n >= 2.0 => *n as u32,
_ => return Err(format!("{}: unit is 2 or more (the part's own sch_x and sch_y place unit 1)", el.call_text())),
};
if part.ideal.is_some() {
return Err(format!("{}: {reference} is an ideal part, which has one unit", el.call_text()));
}
if part.units.iter().any(|(u, _)| *u == n) {
return Err(format!("{}: unit {n} of {reference} is placed twice", el.call_text()));
}
place(s, part, n, el, &[])?;
}
let end = |sel: &Json, el: &El| -> Result<End, String> {
let Some(sel) = sel.as_str() else {
return Err(format!("{}: an end is a selector (\".R1 > .pin1\", \".J1\", \"net.GND\")", el.call_text()));
};
let t = sel.trim();
if let Some(net) = t.strip_prefix("net.") {
if !net.is_empty() && net.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '+' | '-')) {
return Ok(End::Net(net.to_string()));
}
}
let refused = || format!("{}: {sel:?} is not \".REF > .pin\", \".JUNCTION\" or \"net.NAME\"", el.call_text());
let body = t.strip_prefix('.').ok_or_else(refused)?;
match body.split_once('>') {
None if name_ok(body) => {
let node = junctions.get(body).ok_or_else(|| format!("{}: there is no junction {body}", el.call_text()))?;
Ok(End::Pin(node.clone(), VERTEX_PORT.to_string()))
}
Some((part, pin)) => {
let (part, pin) = (part.trim_end(), pin.trim_start().strip_prefix('.').ok_or_else(refused)?);
if !name_ok(part) || !pin_ok(pin) {
return Err(refused());
}
let p = parts.get(part).ok_or_else(|| format!("{}: there is no part {part}", el.call_text()))?;
if p.units.is_empty() {
return Err(format!("{}: {} is not on the sheet (give it sch_x and sch_y)", el.call_text(), p.reference));
}
let Some((count, aliases)) = p.ideal else {
return Ok(End::Pin(p.id.clone(), format!("{LIBRARY_PIN_PORT}{}", pin_number(pin))));
};
let placement = &p.units.iter().find(|(u, _)| *u == 1).expect("an ideal part on the sheet has unit 1").1;
let key = pin.to_lowercase();
let number = aliases.iter().find(|(a, _)| *a == key).map(|(_, n)| n.to_string()).or_else(|| key.chars().all(|c| c.is_ascii_digit()).then(|| key.clone()));
match number.and_then(|n| n.parse::<usize>().ok()) {
Some(n) if n >= 1 && n <= count => Ok(End::Pin(placement.clone(), format!("p{n}"))),
_ => Err(format!("{}: {} has no pin {pin}", el.call_text(), p.reference)),
}
}
None => Err(refused()),
}
};
let mut wires = 0;
for el in later.into_iter().filter(|el| el.tag != "unit") {
match el.tag {
"attachment" => {
refuse_unknown(el, &["name", "role", "file", "mime"])?;
let name = text(el, "name", "the attachment's name (schematic.kicad_sch)")?;
let role = text(el, "role", &format!("one of {}", ROLES.join(", ")))?;
if !ROLES.contains(&role.as_str()) {
return Err(format!("{}: role is one of {}", el.call_text(), ROLES.join(", ")));
}
let file = text(el, "file", "the path of the file it carries, relative to this one")?;
if file.starts_with('/') {
return Err(format!("{}: file is a path relative to this file", el.call_text()));
}
let mut inputs = vec![("name".to_string(), Json::from(name.as_str())), ("role".into(), role.into())];
match el.attr_of("mime") {
None => {}
Some(m @ Json::Str(_)) => inputs.push(("mime".into(), m.clone())),
Some(_) => return Err(format!("{}: mime is a media type", el.call_text())),
}
inputs.push(("file".into(), file.into()));
let id = free(s, &format!("source_{name}"));
s.add(ATTACHMENT, inputs, Some(&id), Some(&name), meta(el))?;
}
"net" => {
refuse_unknown(el, &["name", "pins"])?;
let name = text(el, "name", "the net's name")?;
let pins = match el.attr_of("pins") {
Some(Json::Arr(p)) if !p.is_empty() => p,
_ => return Err(format!("{}: pins is a list of pins (\".C1 > .pin1\")", el.call_text())),
};
let mut ends = Vec::new();
for sel in pins {
let refused = || format!("{}: {} is not \".REF > .pin1\"", el.call_text(), sel.text());
let (part, pin) = sel.as_str().and_then(pin_selector).ok_or_else(refused)?;
let p = parts.get(part).ok_or_else(|| format!("{}: there is no part {part}", el.call_text()))?;
let number = pin_number(pin);
ends.push(match (&p.pins, p.ideal) {
(None, None) => wire(&p.id, &format!("{LIBRARY_PIN_PORT}{number}")),
(None, Some(_)) => return Err(format!("{}: {} is an ideal part drawn on the sheet; a net names pins of a netlist circuit's parts", el.call_text(), p.reference)),
(Some(list), _) => {
let (id, _) = list.iter().find(|(_, n)| n == number).ok_or_else(|| format!("{}: {} has no pin {number}", el.call_text(), p.reference))?;
wire(&p.id, id)
}
});
}
let id = free(s, &format!("net_{name}"));
s.add(NET, channels("pins", ends), Some(&id), Some(&name), meta(el))?;
}
"netlabel" => {
refuse_unknown(el, &["net", "connection"])?;
let text = el.attr_of("net").and_then(Json::as_str).map(str::trim).filter(|t| !t.is_empty()).ok_or("netlabel() needs a net name")?.to_string();
match end(el.attr_of("connection").unwrap_or(&Json::Null), el)? {
End::Net(_) => return Err(format!("{}: a label's connection is a pin or a junction", el.call_text())),
End::Pin(node, port) => label(s, &text, &node, &port, el)?,
}
}
_ => {
refuse_unknown(el, &["from", "to", "path"])?;
let (from, to) = (el.attr_of("from").cloned().unwrap_or(Json::Null), el.attr_of("to").cloned().unwrap_or(Json::Null));
let path = match el.attr_of("path") {
None => vec![from, to],
Some(Json::Arr(p)) if p.len() >= 2 && p.first() == Some(&from) && p.last() == Some(&to) => p.clone(),
Some(_) => return Err(format!("{}: path is the list of selectors from {} to {}", el.call_text(), from.text(), to.text())),
};
let ends = path.iter().map(|p| end(p, el)).collect::<Result<Vec<_>, _>>()?;
for pair in ends.windows(2) {
match (&pair[0], &pair[1]) {
(End::Net(a), End::Net(b)) => return Err(format!("trace() joins two nets ({a}, {b})")),
(End::Net(net), End::Pin(node, port)) | (End::Pin(node, port), End::Net(net)) => label(s, net, node, port, el)?,
(End::Pin(an, ap), End::Pin(bn, bp)) => {
wires += 1;
let id = free(s, &format!("w_{wires}"));
s.add(SCH_WIRE, channels("ends", vec![wire(an, ap), wire(bn, bp)]), Some(&id), Some("Wire"), meta(el))?;
}
}
}
}
}
}
Ok(())
}
fn netlist_part(s: &mut Scope, el: &El, reference: &str) -> Result<Placed, String> {
for p in PLACE.iter().chain(["library"].iter()) {
if el.attr_of(p).is_some() {
let what = if *p == "library" { "library" } else { "place on the sheet" };
return Err(format!("{}: a part that lists its pins is a netlist circuit's; it has no {what}", el.call_text()));
}
}
let raw = match el.attr_of("pins") {
Some(Json::Arr(p)) => p,
_ => return Err(format!("{}: pins is a list of pin numbers ([\"1\", \"2\"]) or of {{ number, name }}", el.call_text())),
};
let mut pins = Vec::new();
for (i, p) in raw.iter().enumerate() {
let refused = || format!("{}: pin {i} is a number (\"1\") or {{ number, name }}, not {}", el.call_text(), p.text());
let (number, name) = match p {
Json::Str(n) => (n.clone(), None),
Json::Obj(entries) if entries.iter().all(|(k, _)| k == "number" || k == "name") => {
let number = p.get("number").and_then(Json::as_str).ok_or_else(refused)?.to_string();
let name = match p.get("name") {
None => None,
Some(Json::Str(n)) => Some(n.clone()),
Some(_) => return Err(refused()),
};
(number, name)
}
_ => return Err(refused()),
};
pins.push((format!("p{}", i + 1), number, name));
}
let symbol = match el.attr_of("symbol") {
None => None,
Some(Json::Str(sym)) if !sym.is_empty() => Some(sym.clone()),
Some(_) => return Err(format!("{}: symbol is a library ref (\"Device:R\")", el.call_text())),
};
let value = value_of(el, "value", "\"LM358\", 1000")?;
let mut inputs = vec![("ref".to_string(), Json::from(reference))];
if let Some(kicad) = kicad_reference_of(el, reference)? {
inputs.push(("reference".into(), kicad));
}
if let Some(v) = value {
inputs.push(("value".into(), v.into()));
}
if let Some(sym) = symbol {
inputs.push(("symbol".into(), sym.into()));
}
inputs.push(("pins".into(), pins_json(&pins)));
if let Some(spice) = spice_of(el)? {
inputs.push(("spice".into(), spice));
}
if let Some(open) = no_connect_of(el)? {
inputs.push(("noConnect".into(), open));
}
if let Some(fields) = fields_of(el)? {
inputs.push(("foreign".into(), fields));
}
let id = s.add(&part_type_for(&pins), inputs, Some(reference), Some(reference), meta(el))?;
let numbered = pins.into_iter().map(|(id, number, _)| (id, number)).collect();
Ok(Placed { reference: reference.to_string(), id, units: Vec::new(), ideal: None, pins: Some(numbered) })
}
enum End {
Net(String),
Pin(String, String),
}
fn name_ok(n: &str) -> bool {
!n.is_empty() && n.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '#' | '-'))
}
fn pin_ok(n: &str) -> bool {
!n.is_empty() && n.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '+' | '-'))
}
fn pin_selector(sel: &str) -> Option<(&str, &str)> {
let (part, pin) = sel.trim().strip_prefix('.')?.split_once('>')?;
let (part, pin) = (part.trim_end(), pin.trim_start().strip_prefix('.')?);
(name_ok(part) && pin_ok(pin)).then_some((part, pin))
}
fn pin_number(pin: &str) -> &str {
match pin.get(..3) {
Some(head) if head.eq_ignore_ascii_case("pin") && pin.len() > 3 => &pin[3..],
_ => pin,
}
}
fn free(s: &Scope, base: &str) -> String {
let b = slug(base);
let (mut i, mut n) = (b.clone(), 2);
while s.has(&i) {
i = format!("{b}_{n}");
n += 1;
}
i
}
fn label(s: &mut Scope, text: &str, node: &str, port: &str, el: &El) -> Result<(), String> {
let id = free(s, &format!("lbl_{text}"));
let inputs = vec![("text".to_string(), Json::from(text)), ("on".into(), wire(node, port))];
s.add(SCH_LABEL, inputs, Some(&id), Some(text), meta(el)).map(|_| ())
}