use super::circuit_checks::declare_circuit_checks;
use super::element::{attributes, elements, fn_name, rust_name};
use super::ir::{slug, Scope};
use super::part_fields::{check_facet, check_offers};
use super::source::meta;
use super::{Declared, Family};
pub use super::{fragment, json, El, Json, Value};
use std::collections::HashMap;
elements! {
board: children;
stack: leaf;
masks: leaf;
graphic: leaf;
text: leaf;
dimension: leaf;
kicad: leaf;
net: leaf;
component: leaf;
trace: leaf;
arc: leaf;
via: leaf;
pour: leaf;
wire: leaf;
netclass: leaf;
diffpair: leaf;
group: leaf;
keepout: leaf;
thermal: leaf;
bus: leaf;
objective: leaf;
fab: leaf;
check: leaf;
accept: leaf;
}
attributes! {
pub trait PcbAttrs {
schematic;
name;
width;
height;
core;
copper;
thickness;
layers;
surface;
label;
domain;
units;
process;
overall_thickness;
polygons;
lib_name;
unit_um_per_db;
kind;
layer;
points;
filled;
arcs;
id;
kicad;
text;
field;
at;
rotation;
size;
size_x;
text_size;
version;
generator;
forms;
code;
footprint;
library;
pcb_x;
pcb_y;
pcb_rotation;
locked;
ref_at;
ref_rot;
value_at;
chart;
uuid;
from;
to;
net;
material;
slack;
segment_uuids;
drill;
diameter;
pads;
terminals;
nets;
clearance;
via_diameter;
via_drill;
current;
criticality;
max_length;
max_vias;
min_width;
edge_clearance;
hole_clearance;
inner;
min_spokes;
impedance;
positive;
negative;
gap;
max_skew;
parts;
region;
near;
max_distance;
conviction;
side;
edge;
mating;
pitch;
no;
watts;
spacing;
away_from;
distance;
weights;
severity;
options;
suppliers;
finish;
mask;
silk;
min_track;
min_space;
min_drill;
min_annular_ring;
min_via_diameter;
min_hole_clearance;
min_hole_to_hole;
min_edge_clearance;
via_in_pad;
max_layers;
thicknesses;
assembly;
inspection;
compliance;
shipping;
check;
rule;
refs;
reason;
}
}
pub(crate) const FAMILY: Family = Family { module: "pcb", roots: &["board"], declare };
pub const BOARD_PART: &str = "eda.footprint";
pub const CONDUCTOR: &str = "eda.conductor";
pub const BOARD_FACT: &str = "eda.boardfact";
pub const BOARD_WIRE: &str = "eda.wire";
pub const BOARD_FOOTPRINTS: &[&str] = &["smd-0805", "axial-7.62", "header-2.54"];
pub const BOARD_LAYERS: &[(u32, &str, &str)] = &[(0, "F.Cu", "signal"), (31, "B.Cu", "signal"), (36, "B.SilkS", "user"), (37, "F.SilkS", "user"), (44, "Edge.Cuts", "user")];
const GRAPHICS: &[(&str, Option<usize>)] = &[("line", Some(2)), ("arc", Some(3)), ("circle", Some(2)), ("rect", Some(2)), ("poly", None)];
const CONDUCTORS: &[&str] = &["trace", "arc", "via", "pour"];
const TRACE_RULES: &[&str] = &["45", "90", "any"];
const FACTS: &[&str] = &["graphic", "text", "dimension", "kicad", "net", "netclass", "diffpair", "group", "keepout", "thermal", "bus", "objective", "fab"];
const CONSTRAINTS: &[&str] = &["netclass", "diffpair", "group", "keepout", "thermal", "bus", "objective"];
const NET_KINDS: &[&str] = &["signal", "power", "ground", "noisy", "sensitive", "highspeed"];
const KEEPOUT_KINDS: &[&str] = &["track", "via", "component", "pour"];
const EDGES: &[&str] = &["left", "right", "top", "bottom"];
fn is_names(v: &Json) -> bool {
matches!(v, Json::Arr(l) if !l.is_empty() && l.iter().all(|x| x.as_str().is_some_and(|s| !s.is_empty())))
}
fn is_box(v: &Json) -> bool {
match v {
Json::Arr(l) if l.len() == 4 => {
let n: Vec<f64> = l.iter().filter_map(finite).collect();
n.len() == 4 && n[0] < n[2] && n[1] < n[3]
}
_ => false,
}
}
fn is_near(s: &str) -> bool {
let name = |t: &str, extra: &str| !t.is_empty() && t.chars().all(|c| c.is_ascii_alphanumeric() || extra.contains(c));
let mut parts = s.split('>').map(str::trim);
let first = parts.next().and_then(|p| p.strip_prefix('.')).is_some_and(|p| name(p, "_#-"));
let rest: Vec<&str> = parts.collect();
first && rest.len() <= 1 && rest.iter().all(|p| p.strip_prefix('.').is_some_and(|p| name(p, "_+-")))
}
fn constraint_fact(el: &El) -> Result<Vec<(String, Json)>, String> {
let mut out: Vec<(String, Json)> = vec![("fact".into(), Json::from(el.tag))];
let unit = |prop: &str| -> Result<Option<f64>, String> {
let v = num(el, prop, false)?;
if v.is_some_and(|v| !(0.0..=1.0).contains(&v)) {
return Err(format!("{}: {} is from 0 to 1", at(el), rust_name(prop)));
}
Ok(v)
};
let names = |prop: &str, required: bool| -> Result<Option<Json>, String> {
match plain(el, prop, is_names, "a list of names")? {
None if required => Err(format!("{} needs {}", at(el), rust_name(prop))),
v => Ok(v),
}
};
fn put(out: &mut Vec<(String, Json)>, k: &str, v: Option<impl Into<Json>>) {
if let Some(v) = v {
out.push((k.into(), v.into()));
}
}
let has = |out: &Vec<(String, Json)>, k: &str| out.iter().any(|(key, _)| key == k);
match el.tag {
"netclass" => {
refuse_unknown(el, &["name", "nets", "kind", "width", "minWidth", "clearance", "edgeClearance", "holeClearance", "inner", "minSpokes", "viaDiameter", "viaDrill", "current", "criticality", "maxLength", "maxVias", "impedance"])?;
let kind = text_of(el, "kind", false)?;
if kind.as_deref().is_some_and(|k| !NET_KINDS.contains(&k)) {
return Err(format!("{}: kind is {}", at(el), NET_KINDS.join(", ")));
}
let max_vias = num(el, "maxVias", false)?;
if max_vias.is_some_and(|v| v.fract() != 0.0 || v < 0.0) {
return Err(format!("{}: {} is a whole number, 0 or more", at(el), rust_name("maxVias")));
}
put(&mut out, "name", text_of(el, "name", true)?);
put(&mut out, "nets", names("nets", true)?);
put(&mut out, "kind", kind);
for k in ["width", "minWidth", "clearance", "edgeClearance", "holeClearance", "viaDiameter", "viaDrill", "current", "maxLength", "impedance"] {
put(&mut out, k, positive(el, k, false)?);
}
put(&mut out, "criticality", unit("criticality")?);
put(&mut out, "maxVias", max_vias);
if let (Some(min), Some(w)) = (num(el, "minWidth", false)?, num(el, "width", false)?) {
if min > w {
return Err(format!("{}: {} is at most width", at(el), rust_name("minWidth")));
}
}
let rules = |v: &Json| matches!(v, Json::Obj(e) if !e.is_empty() && e.iter().all(|(k, x)| ["clearance", "width", "minWidth"].contains(&k.as_str()) && finite(x).is_some_and(|x| x > 0.0)));
if let Some(inner) = plain(el, "inner", rules, "the rules on inner copper layers: { clearance, width, minWidth } (mm)")? {
out.push(("inner".into(), inner));
}
let spokes = num(el, "minSpokes", false)?;
if spokes.is_some_and(|v| v.fract() != 0.0 || !(0.0..=4.0).contains(&v)) {
return Err(format!("{}: {} is a whole number from 0 to 4", at(el), rust_name("minSpokes")));
}
put(&mut out, "minSpokes", spokes);
if let (Some(d), Some(h)) = (num(el, "viaDiameter", false)?, num(el, "viaDrill", false)?) {
if d <= h {
return Err(format!("{}: {} is more than {}", at(el), rust_name("viaDiameter"), rust_name("viaDrill")));
}
}
}
"diffpair" => {
refuse_unknown(el, &["name", "positive", "negative", "gap", "width", "impedance", "maxSkew"])?;
let (p, n) = (text_of(el, "positive", true)?, text_of(el, "negative", true)?);
if p == n {
return Err(format!("{}: positive and negative are two nets", at(el)));
}
put(&mut out, "name", text_of(el, "name", true)?);
put(&mut out, "positive", p);
put(&mut out, "negative", n);
for k in ["gap", "width", "impedance", "maxSkew"] {
put(&mut out, k, positive(el, k, false)?);
}
}
"group" => {
refuse_unknown(el, &["name", "parts", "region", "near", "maxDistance", "conviction", "side", "edge", "mating"])?;
put(&mut out, "name", text_of(el, "name", true)?);
put(&mut out, "parts", names("parts", true)?);
put(&mut out, "region", plain(el, "region", is_box, "[x0, y0, x1, y1] in mm, x0 < x1 and y0 < y1")?);
let near = text_of(el, "near", false)?;
if near.as_deref().is_some_and(|s| !is_near(s)) {
return Err(format!("{}: near is a part (\".J1\") or a pin (\".J1 > .pin5\")", at(el)));
}
let max_distance = positive(el, "maxDistance", false)?;
if max_distance.is_some() && near.is_none() {
return Err(format!("{}: {} needs near", at(el), rust_name("maxDistance")));
}
put(&mut out, "near", near);
put(&mut out, "maxDistance", max_distance);
put(&mut out, "conviction", unit("conviction")?);
let side = text_of(el, "side", false)?;
if side.as_deref().is_some_and(|s| s != "top" && s != "bottom" && s != "any") {
return Err(format!("{}: side is \"top\", \"bottom\" or \"any\"", at(el)));
}
put(&mut out, "side", side);
for k in ["edge", "mating"] {
let v = text_of(el, k, false)?;
if v.as_deref().is_some_and(|e| !EDGES.contains(&e)) {
let edges: Vec<String> = EDGES.iter().map(|e| format!("\"{e}\"")).collect();
return Err(format!("{}: {k} is {}", at(el), edges.join(", ")));
}
put(&mut out, k, v);
}
if has(&out, "mating") && !has(&out, "edge") {
return Err(format!("{}: mating needs edge", at(el)));
}
}
"keepout" => {
refuse_unknown(el, &["name", "points", "layers", "no"])?;
put(&mut out, "name", text_of(el, "name", false)?);
let points: Vec<Json> = point_list(el, "points", 3, None)?.iter().map(|(x, y)| Json::Arr(vec![(*x).into(), (*y).into()])).collect();
out.push(("points".into(), Json::Arr(points)));
if el.attr_of("layers").is_some() {
let layers: Vec<Json> = copper_layers(el, None, None)?.into_iter().map(Json::from).collect();
out.push(("layers".into(), Json::Arr(layers)));
}
let what = format!("a list of {}", KEEPOUT_KINDS.join(", "));
put(&mut out, "no", plain(el, "no", |v| is_names(v) && matches!(v, Json::Arr(l) if l.iter().all(|k| k.as_str().is_some_and(|k| KEEPOUT_KINDS.contains(&k)))), &what)?);
}
"thermal" => {
refuse_unknown(el, &["name", "parts", "watts", "spacing", "awayFrom", "distance"])?;
put(&mut out, "name", text_of(el, "name", true)?);
put(&mut out, "parts", names("parts", true)?);
put(&mut out, "watts", positive(el, "watts", true)?);
put(&mut out, "spacing", positive(el, "spacing", false)?);
put(&mut out, "awayFrom", names("awayFrom", false)?);
put(&mut out, "distance", positive(el, "distance", false)?);
if has(&out, "awayFrom") != has(&out, "distance") {
return Err(format!("{}: give away_from and distance together", at(el)));
}
}
"bus" => {
refuse_unknown(el, &["name", "nets", "pitch"])?;
put(&mut out, "name", text_of(el, "name", true)?);
put(&mut out, "nets", names("nets", true)?);
put(&mut out, "pitch", positive(el, "pitch", false)?);
}
_ => {
refuse_unknown(el, &["weights"])?;
let ok = |v: &Json| matches!(v, Json::Obj(e) if e.iter().all(|(_, x)| finite(x).is_some_and(|x| x >= 0.0)));
match plain(el, "weights", ok, "an object of term → weight (0 or more)")? {
Some(w) => out.push(("weights".into(), w)),
None => return Err(format!("{} needs weights", at(el))),
}
}
}
Ok(out)
}
const SCHEMATIC_ONLY: &[&str] = &["schX", "schY", "schRotation", "resistance", "capacitance", "inductance", "voltage", "current"];
pub fn trace_point_id(index: usize, count: usize) -> String {
if index == 0 {
"start".into()
} else if index + 1 == count {
"end".into()
} else {
format!("p{index}")
}
}
const FAB_CAPABILITIES: &[&str] = &["minTrack", "minSpace", "minDrill", "minAnnularRing", "minViaDiameter", "minHoleClearance", "minHoleToHole", "minEdgeClearance"];
const SIDES: &[&str] = &["top", "bottom"];
const ELECTRICAL: &[&str] = &["flying-probe", "fixture", "none"];
const INSPECTION_KEYS: &[&str] = &["dimensions", "procedure", "acceptance", "sampling", "electrical", "minutes", "ratePerHour", "currency"];
fn fab_fact(el: &El) -> Result<Vec<(String, Json)>, String> {
let fields = [&["suppliers", "finish", "mask", "silk"][..], FAB_CAPABILITIES, &["viaInPad", "maxLayers", "thicknesses", "assembly", "inspection", "compliance", "shipping"]].concat();
refuse_unknown(el, &fields)?;
let w = at(el);
let mut out = vec![("fact".to_string(), Json::from("fab"))];
if let Some(v) = el.attr_of("suppliers") {
out.push(("suppliers".into(), check_offers(&w, v)?));
}
for k in ["finish", "mask", "silk"] {
if let Some(v) = text_of(el, k, false)? {
if v.trim().is_empty() {
return Err(format!("{w}: {k} is text"));
}
out.push((k.into(), v.into()));
}
}
for k in FAB_CAPABILITIES {
if let Some(v) = positive(el, k, false)? {
out.push((k.to_string(), v.into()));
}
}
match el.attr_of("viaInPad") {
None => {}
Some(Json::Bool(b)) => out.push(("viaInPad".into(), Json::Bool(*b))),
Some(_) => return Err(format!("{w}: via_in_pad is true or false")),
}
if let Some(n) = num(el, "maxLayers", false)? {
if !(n.fract() == 0.0 && n >= 1.0) {
return Err(format!("{w}: max_layers is a whole number of copper layers"));
}
out.push(("maxLayers".into(), n.into()));
}
let thick = |v: &Json| matches!(v, Json::Arr(l) if !l.is_empty() && l.iter().all(|x| finite(x).is_some_and(|t| t > 0.0)));
if let Some(t) = plain(el, "thicknesses", thick, "a list of the finished thicknesses the house offers (mm)")? {
out.push(("thicknesses".into(), t));
}
if let Some(a) = el.attr_of("assembly") {
if !is_object(a) || a_keys(a).any(|k| k != "house" && k != "sides") {
return Err(format!("{w}: assembly is {{ house, sides }}"));
}
if a.get("house").is_some() && !matches!(a.get("house"), Some(Json::Str(h)) if !h.trim().is_empty()) {
return Err(format!("{w}: assembly.house is the house that places the parts"));
}
if let Some(sides) = a.get("sides") {
let ok = match sides {
Json::Arr(l) => {
let names: Vec<&str> = l.iter().filter_map(Json::as_str).filter(|s| SIDES.contains(s)).collect();
!l.is_empty() && names.len() == l.len() && names.iter().enumerate().all(|(i, s)| !names[..i].contains(s))
}
_ => false,
};
if !ok {
return Err(format!(r#"{w}: assembly.sides is a list of "top", "bottom""#));
}
}
out.push(("assembly".into(), a.clone()));
}
if let Some(i) = el.attr_of("inspection") {
if !is_object(i) {
return Err(format!("{w}: inspection is an object ({{ {} }})", INSPECTION_KEYS.join(", ")));
}
if let Some(k) = a_keys(i).find(|k| !INSPECTION_KEYS.contains(k)) {
return Err(format!("{w}: inspection.{k} is not read (it takes {})", INSPECTION_KEYS.join(", ")));
}
if i.get("electrical").is_some_and(|e| !e.as_str().is_some_and(|e| ELECTRICAL.contains(&e))) {
return Err(format!("{w}: inspection.electrical is one of {}", ELECTRICAL.join(", ")));
}
for k in ["procedure", "acceptance", "sampling"] {
if i.get(k).is_some_and(|v| !v.as_str().is_some_and(|s| !s.trim().is_empty())) {
return Err(format!("{w}: inspection.{k} is text"));
}
}
for k in ["minutes", "ratePerHour"] {
if i.get(k).is_some_and(|v| !v.as_f64().is_some_and(|n| n >= 0.0)) {
return Err(format!("{w}: inspection.{k} is a number, 0 or more"));
}
}
if i.get("currency").is_some_and(|c| !c.as_str().is_some_and(|c| c.len() == 3 && c.bytes().all(|b| b.is_ascii_uppercase()))) {
return Err(format!(r#"{w}: inspection.currency is an ISO 4217 code ("USD")"#));
}
out.push(("inspection".into(), i.clone()));
}
for k in ["compliance", "shipping"] {
if let Some(v) = el.attr_of(k) {
out.push((k.into(), check_facet(&w, k, v)?));
}
}
Ok(out)
}
fn a_keys(v: &Json) -> impl Iterator<Item = &str> {
let entries: &[(String, Json)] = match v {
Json::Obj(e) => e,
_ => &[],
};
entries.iter().map(|(k, _)| k.as_str())
}
fn at(el: &El) -> String {
match el.attr_of("name") {
Some(v @ Json::Str(_)) => format!("{}().name({})", fn_name(el.tag), v.text()),
_ => format!("{}()", fn_name(el.tag)),
}
}
fn refuse_unknown(el: &El, allowed: &[&str]) -> Result<(), String> {
for (k, _) in &el.attrs {
if allowed.contains(&k.as_str()) {
continue;
}
if SCHEMATIC_ONLY.contains(&k.as_str()) {
return Err(format!("{}: {} is the schematic's; a board says only where its parts sit and where its copper runs", at(el), rust_name(k)));
}
return Err(format!("{}: {} is not read on a board", at(el), rust_name(k)));
}
Ok(())
}
fn finite(v: &Json) -> Option<f64> {
v.as_f64().filter(|n| n.is_finite())
}
fn num(el: &El, prop: &str, required: bool) -> Result<Option<f64>, String> {
match el.attr_of(prop) {
None if required => Err(format!("{} needs {}", at(el), rust_name(prop))),
None => Ok(None),
Some(v) => finite(v).map(Some).ok_or_else(|| format!("{}: {} is a number (mm or degrees), not {}", at(el), rust_name(prop), v.text())),
}
}
fn positive(el: &El, prop: &str, required: bool) -> Result<Option<f64>, String> {
let v = num(el, prop, required)?;
if v.is_some_and(|v| v <= 0.0) {
return Err(format!("{}: {} is more than 0", at(el), rust_name(prop)));
}
Ok(v)
}
fn text_of(el: &El, prop: &str, required: bool) -> Result<Option<String>, String> {
match el.attr_of(prop) {
None if required => Err(format!("{} needs {}", at(el), rust_name(prop))),
None => Ok(None),
Some(Json::Str(s)) => Ok(Some(s.clone())),
Some(v) => Err(format!("{}: {} is text, not {}", at(el), rust_name(prop), v.text())),
}
}
fn xy(x: f64, y: f64) -> Json {
Json::obj().with("x", x).with("y", y)
}
fn pair(v: &Json) -> Option<(f64, f64)> {
match v {
Json::Arr(p) if p.len() == 2 => Some((finite(&p[0])?, finite(&p[1])?)),
_ => None,
}
}
fn point_list(el: &El, prop: &str, least: usize, count: Option<usize>) -> Result<Vec<(f64, f64)>, String> {
let list = match el.attr_of(prop) {
Some(Json::Arr(list)) if list.len() >= least && count.is_none_or(|c| list.len() == c) => list,
_ => {
let n = count.map(|c| c.to_string()).unwrap_or_else(|| format!("at least {least}"));
return Err(format!("{}: {} is a list of {n} [x, y]", at(el), rust_name(prop)));
}
};
list.iter()
.enumerate()
.map(|(i, p)| pair(p).ok_or_else(|| format!("{}: point {i} is [x, y] in mm, not {}", at(el), p.text())))
.collect()
}
fn at_point(el: &El, prop: &str) -> Result<Json, String> {
let v = el.attr_of(prop).unwrap_or(&Json::Null);
let (x, y) = pair(v).ok_or_else(|| format!("{}: {} is [x, y] in mm, not {}", at(el), rust_name(prop), if *v == Json::Null { "undefined".into() } else { v.text() }))?;
Ok(xy(x, y))
}
fn copper(layer: &str) -> bool {
layer.strip_suffix(".Cu").is_some_and(|h| !h.is_empty() && h.chars().all(|c| c.is_ascii_alphanumeric()))
}
fn on_board(el: &El, layer: &str, board_copper: &[String]) -> Result<(), String> {
if board_copper.iter().any(|l| l == layer) {
return Ok(());
}
let has = if board_copper.is_empty() { "none".to_string() } else { board_copper.join(", ") };
Err(format!("{}: the board has no copper layer {layer} (it has {has})", at(el)))
}
fn copper_layers(el: &El, board_copper: Option<&[String]>, fallback: Option<&[&str]>) -> Result<Vec<String>, String> {
let layers: Option<Vec<Json>> = match el.attr_of("layers") {
Some(Json::Arr(l)) => Some(l.clone()),
Some(_) => None,
None => fallback.map(|f| f.iter().map(|l| Json::from(*l)).collect()),
};
let layers: Vec<String> = match layers {
Some(l) if !l.is_empty() && l.iter().all(|x| x.as_str().is_some_and(copper)) => l.iter().map(|x| x.as_str().unwrap_or_default().to_string()).collect(),
_ => return Err(format!("{}: layers is a list of copper layers (\"F.Cu\", \"In1.Cu\", \"B.Cu\")", at(el))),
};
if let Some(board_copper) = board_copper {
for l in &layers {
on_board(el, l, board_copper)?;
}
}
Ok(layers)
}
fn kicad_of(el: &El, prop: &str, inputs: &mut Vec<(String, Json)>) -> Result<(), String> {
if let Some(v) = text_of(el, prop, false)? {
inputs.push(("kicad".into(), v.into()));
}
Ok(())
}
fn plain(el: &El, prop: &str, check: impl Fn(&Json) -> bool, what: &str) -> Result<Option<Json>, String> {
match el.attr_of(prop) {
None => Ok(None),
Some(v) if check(v) => Ok(Some(v.clone())),
Some(_) => Err(format!("{}: {} is {what}", at(el), rust_name(prop))),
}
}
fn is_object(v: &Json) -> bool {
matches!(v, Json::Obj(_))
}
fn is_mask_polygons(v: &Json) -> bool {
let Json::Arr(polygons) = v else { return false };
!polygons.is_empty()
&& polygons.iter().all(|p| match p {
Json::Obj(fields) => {
let layer = fields.iter().find(|(k, _)| k == "layer").map(|(_, v)| v);
let datatype = fields.iter().find(|(k, _)| k == "datatype").map(|(_, v)| v);
let int = |v: Option<&Json>| matches!(v, Some(Json::Num(n)) if n.fract() == 0.0 && *n >= 0.0);
let points = fields.iter().find(|(k, _)| k == "points").map(|(_, v)| v);
int(layer)
&& int(datatype)
&& fields.iter().all(|(k, _)| ["layer", "datatype", "points"].contains(&k.as_str()))
&& match points {
Some(Json::Arr(ps)) if ps.len() >= 3 => ps.iter().all(|q| matches!(q, Json::Arr(xy) if xy.len() == 2 && xy.iter().all(|c| matches!(c, Json::Num(n) if n.is_finite())))),
_ => false,
}
}
_ => false,
})
}
fn is_str(v: Option<&Json>) -> bool {
matches!(v, Some(Json::Str(_)))
}
fn ref_name(s: &str) -> bool {
!s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '#' | '-'))
}
fn pin_name(s: &str) -> bool {
!s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '+' | '-'))
}
fn one_selector(sel: &str) -> Option<&str> {
let n = sel.trim().strip_prefix('.')?;
ref_name(n).then_some(n)
}
fn two_selector(sel: &str) -> Option<(&str, &str)> {
let (owner, which) = sel.trim().strip_prefix('.')?.split_once('>')?;
let (owner, which) = (owner.trim_end(), which.trim_start().strip_prefix('.')?);
(ref_name(owner) && pin_name(which)).then_some((owner, which))
}
fn footprint_ref(fp: &str) -> bool {
match fp.split_once(':') {
Some((lib, name)) => !lib.is_empty() && !name.is_empty() && !name.contains(':') && !name.contains('/'),
None => false,
}
}
fn declare(root: El) -> Result<Declared, String> {
if root.attr_of("schematic").is_none() {
return Err("board(): schematic is the schematic file's path, relative to this file (a board in code names its schematic)".into());
}
declare_board_file(&root, None).map(Declared::Graph)
}
pub fn declare_board_file(root: &El, name: Option<&str>) -> Result<Json, String> {
refuse_unknown(root, &["schematic", "name", "width", "height", "core", "copper", "thickness", "layers", "surface"])?;
let schematic = match root.attr_of("schematic") {
Some(Json::Str(s)) if !s.trim().is_empty() && !s.starts_with('/') => s.clone(),
_ => return Err("board(): schematic is the schematic file's path, relative to this file".into()),
};
let title = match root.attr_of("name") {
Some(Json::Str(n)) => n.clone(),
_ => name.unwrap_or("Board").to_string(),
};
let mut s = Scope::new(
&format!("eda:{}", slug(&title)),
Json::obj().with("domain", "eda").with("rung", "board").with("name", title.as_str()).with("schematic", schematic.as_str()),
);
let has_board = declare_board(&mut s, root)?;
let mut graph = s.build();
let outputs = if has_board { vec![Json::from("board")] } else { sinks(&graph) };
if !outputs.is_empty() {
let meta = graph.remove("meta").unwrap_or_else(Json::obj);
graph.set("outputs", outputs);
graph.set("meta", meta);
}
Ok(graph)
}
fn sinks(graph: &Json) -> Vec<Json> {
let Some(Json::Obj(nodes)) = graph.get("nodes") else { return Vec::new() };
let used: Vec<&str> = nodes
.iter()
.filter_map(|(_, n)| match n.get("inputs") {
Some(Json::Obj(inputs)) => Some(inputs.iter().filter_map(|(_, v)| v.get("wire").and_then(|w| w.get("node")).and_then(Json::as_str))),
_ => None,
})
.flatten()
.collect();
nodes.iter().filter(|(id, _)| !used.contains(&id.as_str())).map(|(id, _)| Json::from(id.as_str())).collect()
}
enum Owner<'a> {
Component,
Conductor(&'a El, String),
}
fn declare_board(s: &mut Scope, root: &El) -> Result<bool, String> {
let children: Vec<&El> = declare_circuit_checks(&mut s.meta, root.child_elements().collect())?;
let (w, h) = (positive(root, "width", false)?, positive(root, "height", false)?);
let (core, copper_mm, thickness) = (positive(root, "core", false)?, positive(root, "copper", false)?, positive(root, "thickness", false)?);
let layers = plain(
root,
"layers",
|v| matches!(v, Json::Arr(l) if !l.is_empty() && l.iter().all(|l| is_object(l) && is_str(l.get("name")) && l.get("ordinal").and_then(finite).is_some())),
"the layer table: [{ ordinal, name, type, userName }, …]",
)?;
if w.is_none() != h.is_none() {
return Err("board(): give width and height together".into());
}
if core.is_none() != copper_mm.is_none() {
return Err("board(): give core and copper together".into());
}
let stacks: Vec<&El> = children.iter().copied().filter(|el| el.tag == "stack").collect();
if stacks.len() > 1 {
return Err("a board has one stack()".into());
}
if !stacks.is_empty() && core.is_some() {
return Err("board(): core and copper are a two-layer stack(); give one or the other".into());
}
if thickness.is_some() && core.is_some() {
return Err("board(): core and copper say the thickness".into());
}
if core.is_some() && w.is_none() {
return Err("board(): core and copper need the outline (width and height)".into());
}
let surface = plain(
root,
"surface",
|v| match v {
Json::Obj(entries) => is_str(v.get("cadRef")) && v.get("domain").is_some_and(is_object) && entries.iter().all(|(k, _)| ["cadRef", "domain", "trims", "curvedTrims"].contains(&k.as_str())),
_ => false,
},
"the CAD faces the board is on: { cadRef, domain, trims, curvedTrims }",
)?;
let has_board = w.is_some()
|| thickness.is_some()
|| layers.is_some()
|| surface.is_some()
|| !stacks.is_empty()
|| children.iter().any(|el| ["graphic", "text", "dimension", "kicad"].contains(&el.tag));
let mut board_copper: Vec<String> = Vec::new();
fn has_copper(board_copper: &mut Vec<String>, name: &str) {
if copper(name) && !board_copper.iter().any(|l| l == name) {
board_copper.push(name.to_string());
}
}
match &layers {
Some(Json::Arr(table)) => table.iter().filter_map(|l| l.get("name").and_then(|n| n.as_str())).for_each(|n| has_copper(&mut board_copper, n)),
_ => BOARD_LAYERS.iter().for_each(|(_, n, _)| has_copper(&mut board_copper, n)),
}
let mut stack_thickness = None;
if let (Some(core), Some(cu)) = (core, copper_mm) {
has_copper(&mut board_copper, "F.Cu");
has_copper(&mut board_copper, "B.Cu");
stack_thickness = Some(core + 2.0 * cu);
let layer = |name: &str, role: &str, t: f64| Json::obj().with("name", name).with("role", role).with("thickness", t);
let inputs = vec![
("id".to_string(), Json::from("stack")),
("domain".into(), "pcb".into()),
("units".into(), "mm".into()),
("layers".into(), Json::Arr(vec![layer("F.Cu", "conductor", cu), layer("core", "dielectric", core), layer("B.Cu", "conductor", cu)])),
];
s.add("eda.stack", inputs, Some("stack"), Some("Cross-section"), meta(root))?;
}
for el in &stacks {
refuse_unknown(el, &["name", "label", "domain", "units", "process", "layers", "overallThickness"])?;
let stack_layers = plain(
el,
"layers",
|v| matches!(v, Json::Arr(l) if l.iter().all(|l| is_object(l) && is_str(l.get("name")) && is_str(l.get("role")))),
"the layers, top first: [{ name, role, thickness, … }, …]",
)?
.ok_or("stack() needs layers")?;
if let Json::Arr(rows) = &stack_layers {
for l in rows {
if let (Some(Json::Str(name)), Some(Json::Str(role))) = (l.get("name"), l.get("role")) {
if role == "conductor" {
has_copper(&mut board_copper, name);
}
}
}
}
let domain = text_of(el, "domain", false)?.unwrap_or_else(|| "pcb".into());
let units = text_of(el, "units", false)?.unwrap_or_else(|| "mm".into());
if domain != "pcb" && domain != "ic" {
return Err("stack(): domain is \"pcb\" or \"ic\"".into());
}
if !["mm", "um", "nm"].contains(&units.as_str()) {
return Err("stack(): units is \"mm\", \"um\" or \"nm\"".into());
}
let process = plain(el, "process", is_object, "an object ({ name, … })")?;
let mut inputs = vec![
("id".to_string(), Json::from(text_of(el, "name", false)?.unwrap_or_else(|| "stack".into()))),
("domain".into(), domain.into()),
("units".into(), units.into()),
("layers".into(), stack_layers),
];
if let Some(p) = process {
inputs.push(("process".into(), p));
}
if el.attr_of("overallThickness").is_some() {
inputs.push(("overallThickness".into(), positive(el, "overallThickness", false)?.unwrap_or_default().into()));
}
let label = text_of(el, "label", false)?.unwrap_or_else(|| "Cross-section".into());
s.add("eda.stack", inputs, Some("stack"), Some(&label), meta(el))?;
}
if has_board {
let layers = layers.unwrap_or_else(|| {
Json::Arr(BOARD_LAYERS.iter().map(|(o, n, t)| Json::obj().with("ordinal", *o).with("name", *n).with("type", *t)).collect())
});
let mut inputs = vec![("layers".to_string(), layers)];
if let Some(t) = stack_thickness.or(thickness) {
inputs.push(("thicknessMm".into(), t.into()));
}
if core.is_some() || !stacks.is_empty() {
inputs.push(("stack".into(), super::ir::wire("stack", "stack")));
}
if let (Some(w), Some(h)) = (w, h) {
let outline = Json::obj()
.with("id", "outline")
.with("kind", "rect")
.with("points", vec![xy(0.0, 0.0), xy(w, h)])
.with("widthMm", 0.05)
.with("layer", "Edge.Cuts")
.with("filled", false);
inputs.push(("boardArtwork".into(), Json::obj().with("graphics", vec![outline]).with("texts", Json::Arr(Vec::new()))));
}
if let Some(sf) = &surface {
inputs.push(("surfaceMount".into(), sf.clone()));
}
s.add("eda.board", inputs, Some("board"), Some("Board"), meta(root))?;
}
let mut components: Vec<String> = Vec::new();
let mut conductors: HashMap<String, &El> = HashMap::new();
let mut nets: Vec<String> = Vec::new();
let mut constraint_names: Vec<String> = Vec::new();
let mut wire_names: Vec<String> = Vec::new();
let mut kicad_forms = 0;
let mut fabs = 0;
for el in &children {
let nm = el.attr_of("name");
if el.tag == "component" {
let nm = match nm {
Some(Json::Str(n)) if !n.is_empty() => n.clone(),
_ => return Err("component() needs the name of the schematic's part".into()),
};
if components.contains(&nm) || conductors.contains_key(&nm) {
return Err(format!("two elements are called {nm}"));
}
components.push(nm);
} else if CONDUCTORS.contains(&el.tag) {
let Some(nm) = nm else { continue };
let nm = match nm {
Json::Str(n) if !n.is_empty() && n.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') => n.clone(),
_ => return Err(format!("{}: a name is letters, digits, _ and -", at(el))),
};
if components.contains(&nm) || conductors.contains_key(&nm) {
return Err(format!("two elements are called {nm}"));
}
conductors.insert(nm, el);
} else if el.tag == "net" {
let nm = match nm {
Some(Json::Str(n)) if !n.is_empty() => n.clone(),
_ => return Err("net() needs the name of the schematic's net".into()),
};
if nets.contains(&nm) {
return Err(format!("two net() elements name {nm}"));
}
nets.push(nm);
} else if el.tag == "kicad" {
kicad_forms += 1;
if kicad_forms > 1 {
return Err("a board has one kicad()".into());
}
} else if el.tag == "fab" {
fabs += 1;
if fabs > 1 {
return Err("a board has one fab()".into());
}
} else if CONSTRAINTS.contains(&el.tag) {
let key = match (el.tag, nm) {
("objective", _) => Some("objective".to_string()),
(tag, Some(Json::Str(n))) => Some(format!("{tag}:{n}")),
_ => None,
};
if let Some(key) = key {
if constraint_names.contains(&key) {
return Err(if el.tag == "objective" { "a board has one objective()".to_string() } else { format!("two {}() elements are called {}", el.tag, key.split_once(':').map(|(_, n)| n).unwrap_or_default()) });
}
constraint_names.push(key);
}
} else if el.tag == "wire" {
if let Some(Json::Str(n)) = nm {
if wire_names.contains(n) {
return Err(format!("two wire() elements are called {n}"));
}
wire_names.push(n.clone());
}
} else if el.tag != "stack" && el.tag != "masks" && !FACTS.contains(&el.tag) {
return Err(format!("{}() is not read on a board (see commandagi::design::pcb)", fn_name(el.tag)));
}
}
let mut ids: Vec<String> = Vec::new();
let mut n = 0;
for el in &children {
if !CONDUCTORS.contains(&el.tag) {
continue;
}
match el.attr_of("name").and_then(Json::as_str) {
Some(nm) => ids.push(nm.to_string()),
None => loop {
n += 1;
let id = format!("cu_{n}");
if !conductors.contains_key(&id) && !components.contains(&id) {
ids.push(id);
break;
}
},
}
}
let mut ids = ids.into_iter();
let owner_of = |name: &str| -> Option<Owner> {
if components.iter().any(|c| c == name) {
return Some(Owner::Component);
}
conductors.get(name).map(|el| Owner::Conductor(el, name.to_string()))
};
let point_count = |el: &El| -> Result<usize, String> { if el.tag == "arc" { Ok(3) } else { point_list(el, "points", 2, None).map(|p| p.len()) } };
let end = |sel: &Json, el: &El, point: usize| -> Result<Json, String> {
let Some(sel) = sel.as_str() else {
return Err(format!("{}: an end is a selector (\".R1 > .pin2\", \".V1\", \".T1 > .end\")", at(el)));
};
let p = Json::obj().with("point", point as f64);
if let Some(name) = one_selector(sel) {
return match owner_of(name) {
Some(Owner::Conductor(via, id)) if via.tag == "via" => Ok(p.with("via", id)),
_ => Err(format!("{}: there is no via {name}", at(el))),
};
}
let (owner, which) = two_selector(sel).ok_or_else(|| format!("{}: {} is not \".REF > .pin1\", \".VIA\" or \".TRACE > .end\"", at(el), Json::from(sel).text()))?;
match owner_of(owner) {
Some(Owner::Component) => {
let number = match which.get(..3) {
Some(head) if head.eq_ignore_ascii_case("pin") && which.len() > 3 => &which[3..],
_ => which,
};
Ok(p.with("ref", owner).with("number", number))
}
Some(Owner::Conductor(run, id)) if run.tag == "trace" || run.tag == "arc" => {
let count = point_count(run)?;
let index = match which {
"start" => Some(0),
"end" => count.checked_sub(1),
w if w.chars().all(|c| c.is_ascii_digit()) => w.parse::<usize>().ok(),
_ => None,
};
match index {
Some(i) if i < count => Ok(p.with("run", id).with("runPoint", trace_point_id(i, count))),
_ => Err(format!("{}: trace {owner} has no point {which}", at(el))),
}
}
_ => Err(format!("{}: there is no component or trace {owner}", at(el))),
}
};
let net_of = |el: &El, inputs: &mut Vec<(String, Json)>| -> Result<(), String> {
if let Some(v) = text_of(el, "net", false)? {
if v.trim().is_empty() {
return Err(format!("{}: net names the schematic's net", at(el)));
}
inputs.push(("net".into(), v.into()));
}
Ok(())
};
let uuid_of = |el: &El, inputs: &mut Vec<(String, Json)>| -> Result<(), String> {
if let Some(v) = text_of(el, "uuid", false)? {
inputs.push(("uuid".into(), v.into()));
}
Ok(())
};
for el in &children {
let el: &El = el;
match el.tag {
"masks" => {
refuse_unknown(el, &["name", "label", "libName", "unitUmPerDb", "polygons"])?;
let polygons = plain(el, "polygons", is_mask_polygons, "the mask layout's polygons: [{ layer, datatype, points: [[x, y], …] }, …], points in micrometres")?
.ok_or("masks() needs polygons")?;
let lib_name = text_of(el, "libName", false)?;
let mut inputs = vec![("polygons".to_string(), polygons), ("unitUmPerDb".into(), positive(el, "unitUmPerDb", true)?.unwrap_or_default().into())];
if let Some(l) = &lib_name {
inputs.push(("libName".into(), l.clone().into()));
}
let id = text_of(el, "name", false)?.unwrap_or_else(|| "masks".into());
let label = text_of(el, "label", false)?.or_else(|| lib_name.clone()).unwrap_or_else(|| "Masks".into());
s.add("eda.masks", inputs, Some(&id), Some(&label), meta(el))?;
}
"component" => {
refuse_unknown(el, &["name", "footprint", "library", "pcbX", "pcbY", "pcbRotation", "layer", "locked", "refAt", "refRot", "valueAt", "chart", "uuid", "kicad"])?;
let reference = el.attr_of("name").and_then(Json::as_str).unwrap_or_default().to_string();
let fp = el.attr_of("footprint");
let fp_text = fp.and_then(Json::as_str);
let shown = |v: Option<&Json>| v.map(Json::text).unwrap_or_else(|| "undefined".into());
let library = el.attr_of("library");
if let Some(library) = library {
let pretty = library.as_str().is_some_and(|l| {
let l = l.to_lowercase();
let file = l.rsplit_once('/').is_some_and(|(dir, name)| dir.ends_with(".pretty") && name.len() > ".kicad_mod".len() && name.ends_with(".kicad_mod"));
l.ends_with(".pretty") || l.ends_with(".pretty/") || file
});
if !pretty {
return Err(format!("{}: library names a footprint library folder (a .pretty) or one .kicad_mod in it, not {}", at(el), library.text()));
}
let bare = |f: &str| !f.is_empty() && !f.contains(':') && !f.contains('/');
if !fp_text.is_some_and(|f| footprint_ref(f) || bare(f)) {
return Err(format!(
"{}: a library footprint is its ref, \"Library:Footprint\" (\"Package_SO:SOIC-8\"), or the bare name KiCad gave it (\"POLY\"), not {}",
at(el),
shown(fp)
));
}
} else if !fp_text.is_some_and(|f| BOARD_FOOTPRINTS.contains(&f) || footprint_ref(f)) {
return Err(format!(
"{}: footprint is one of {}, or a library footprint by its ref (\"Package_SO:SOIC-8\") with its library, not {}",
at(el),
BOARD_FOOTPRINTS.join(", "),
shown(fp)
));
}
let fp = fp_text.unwrap_or_default();
let named = library.is_none() && !BOARD_FOOTPRINTS.contains(&fp);
if named && (el.attr_of("pcbX").is_some() || el.attr_of("pcbY").is_some()) {
return Err(format!("{}: a footprint is placed with its pads: name its library (a .pretty folder)", at(el)));
}
let (x, y, rot) = (num(el, "pcbX", false)?, num(el, "pcbY", false)?, num(el, "pcbRotation", false)?);
let side = el.attr_of("layer");
if side.is_some_and(|s| s.as_str() != Some("top") && s.as_str() != Some("bottom")) {
return Err(format!("{}: layer is \"top\" or \"bottom\"", at(el)));
}
if x.is_none() != y.is_none() {
return Err(format!("{}: give pcb_x and pcb_y together", at(el)));
}
if x.is_none() && (rot.is_some() || side.is_some()) {
return Err(format!("{}: pcb_rotation and layer need pcb_x and pcb_y", at(el)));
}
let ref_at = el.attr_of("refAt");
if ref_at.is_some_and(|v| !matches!(v, Json::Arr(l) if l.len() == 2 && l.iter().all(|n| finite(n).is_some()))) {
return Err(format!("{}: ref_at is [x, y] in mm, in the footprint's own frame", at(el)));
}
if ref_at.is_some() && x.is_none() {
return Err(format!("{}: ref_at needs pcb_x and pcb_y", at(el)));
}
let ref_rot = num(el, "refRot", false)?;
if ref_rot.is_some() && x.is_none() {
return Err(format!("{}: ref_rot needs pcb_x and pcb_y", at(el)));
}
let value_at = el.attr_of("valueAt");
if value_at.is_some_and(|v| !matches!(v, Json::Arr(l) if l.len() == 2 && l.iter().all(|n| finite(n).is_some()))) {
return Err(format!("{}: value_at is [x, y] in mm, in the footprint's own frame", at(el)));
}
if value_at.is_some() && x.is_none() {
return Err(format!("{}: value_at needs pcb_x and pcb_y", at(el)));
}
let locked = match el.attr_of("locked") {
None => false,
Some(Json::Bool(true)) => true,
Some(_) => return Err(format!("{}: locked is true or left out", at(el))),
};
let chart = text_of(el, "chart", false)?;
if chart.is_some() && surface.is_none() {
return Err(format!("{}: chart names a face of the board's surface, and the board() has no surface", at(el)));
}
if chart.is_some() && x.is_none() {
return Err(format!("{}: chart needs pcb_x and pcb_y", at(el)));
}
let mut inputs = vec![("ref".to_string(), Json::from(reference.as_str()))];
match library.and_then(Json::as_str) {
Some(l) => {
inputs.push(("footprint".into(), fp.into()));
inputs.push(("library".into(), l.strip_suffix('/').unwrap_or(l).into()));
}
None if named => inputs.push(("footprint".into(), fp.into())),
None => inputs.push(("footprint".into(), format!("Authored:{fp}").into())),
}
if let (Some(x), Some(y)) = (x, y) {
let side = side.and_then(Json::as_str).unwrap_or("top");
inputs.push(("placement".into(), Json::obj().with("x", x).with("y", y).with("rot", rot.unwrap_or(0.0)).with("side", side)));
}
if locked {
inputs.push(("locked".into(), Json::Bool(true)));
}
if let Some(r) = ref_at {
inputs.push(("refAt".into(), r.clone()));
}
if let Some(r) = ref_rot {
inputs.push(("refRot".into(), Json::from(r)));
}
if let Some(r) = value_at {
inputs.push(("valueAt".into(), r.clone()));
}
if let Some(c) = chart {
inputs.push(("surfaceMount".into(), Json::obj().with("chart", c)));
}
uuid_of(el, &mut inputs)?;
kicad_of(el, "kicad", &mut inputs)?;
s.add(BOARD_PART, inputs, Some(&format!("fp_{reference}")), Some(&reference), meta(el))?;
}
"trace" | "arc" => {
let is_trace = el.tag == "trace";
let mut allowed = vec!["name", "layer", "width", "points", "from", "to", "net", "uuid", "kicad"];
if is_trace {
allowed.extend(["segmentUuids", "surface", "rule"]);
}
refuse_unknown(el, &allowed)?;
let rule = match el.attr_of("rule") {
None => "any".to_string(),
Some(Json::Str(r)) if TRACE_RULES.contains(&r.as_str()) => r.clone(),
Some(other) => return Err(format!("{}: rule is \"45\", \"90\" or \"any\", not {}", at(el), other.text())),
};
let on_surface = match el.attr_of("surface") {
None => false,
Some(Json::Bool(true)) => true,
Some(_) => return Err(format!("{}: surface is true or left out", at(el))),
};
if on_surface && surface.is_none() {
return Err(format!("{}: surface runs the trace on the board's surface, and the board() has no surface", at(el)));
}
let pts = if is_trace { point_list(el, "points", 2, None)? } else { point_list(el, "points", 3, Some(3))? };
let layer = match el.attr_of("layer") {
Some(Json::Str(l)) if copper(l) => l.clone(),
_ => return Err(format!("{}: layer is a copper layer (\"F.Cu\", \"In1.Cu\", \"B.Cu\")", at(el))),
};
on_board(el, &layer, &board_copper)?;
let count = pts.len();
let mut terminals = Vec::new();
if let Some(from) = el.attr_of("from") {
terminals.push(end(from, el, 0)?);
}
if let Some(to) = el.attr_of("to") {
terminals.push(end(to, el, count - 1)?);
}
let segment_uuids = plain(el, "segmentUuids", |v| matches!(v, Json::Arr(l) if l.iter().all(|u| u.as_str().is_some())), "a list of uuids, one per segment")?;
let points: Vec<Json> = pts.iter().enumerate().map(|(i, (x, y))| xy(*x, *y).with("id", trace_point_id(i, count))).collect();
let mut inputs = vec![
("kind".to_string(), Json::from(if is_trace { "run" } else { "arc" })),
("points".into(), points.into()),
("widthMm".into(), positive(el, "width", true)?.unwrap_or_default().into()),
("layer".into(), layer.into()),
];
if is_trace {
inputs.push(("rule".into(), rule.into()));
}
if !terminals.is_empty() {
inputs.push(("terminals".into(), terminals.into()));
}
if let Some(u) = segment_uuids {
inputs.push(("segmentUuids".into(), u));
}
if on_surface {
let domain = surface.as_ref().and_then(|sf| sf.get("domain")).cloned().unwrap_or(Json::Null);
inputs.push(("mount".into(), Json::obj().with("kind", "unwrap").with("domain", domain)));
}
uuid_of(el, &mut inputs)?;
net_of(el, &mut inputs)?;
kicad_of(el, "kicad", &mut inputs)?;
let id = ids.next().expect("each conductor has an id");
s.add(CONDUCTOR, inputs, Some(&id), Some(if is_trace { "Trace" } else { "Arc" }), meta(el))?;
}
"via" => {
refuse_unknown(el, &["name", "pcbX", "pcbY", "drill", "diameter", "layers", "pads", "net", "uuid", "kicad"])?;
let layers = copper_layers(el, Some(&board_copper), Some(&["F.Cu", "B.Cu"]))?;
if layers.len() < 2 {
return Err(format!("{}: layers is two or more copper layers", at(el)));
}
if layers.first() == layers.last() {
return Err(format!("{}: the ends of a via are two layers, not {} twice", at(el), layers[0]));
}
let drill = positive(el, "drill", true)?.unwrap_or_default();
let diameter = positive(el, "diameter", true)?.unwrap_or_default();
if diameter <= drill {
return Err(format!("{}: the diameter is more than the drill", at(el)));
}
let pads: Vec<Json> = match el.attr_of("pads") {
None => Vec::new(),
Some(Json::Arr(p)) if !p.is_empty() => p.clone(),
Some(_) => return Err(format!("{}: pads is a list of pins (\".R1 > .pin2\")", at(el))),
};
let mut pad_refs = Vec::new();
for p in &pads {
let t = end(p, el, 0)?;
match (t.get("ref"), t.get("number")) {
(Some(r), Some(n)) => pad_refs.push(Json::obj().with("ref", r.clone()).with("number", n.clone())),
_ => return Err(format!("{}: a via is plated into a pad (\".R1 > .pin2\"), not {}", at(el), p.text())),
}
}
let (x, y) = (num(el, "pcbX", true)?.unwrap_or_default(), num(el, "pcbY", true)?.unwrap_or_default());
let mut inputs = vec![
("kind".to_string(), Json::from("via")),
("points".into(), vec![xy(x, y)].into()),
("drillMm".into(), drill.into()),
("padDiameterMm".into(), diameter.into()),
("layers".into(), layers.into_iter().map(Json::from).collect::<Vec<_>>().into()),
];
if !pad_refs.is_empty() {
inputs.push(("pads".into(), pad_refs.into()));
}
uuid_of(el, &mut inputs)?;
net_of(el, &mut inputs)?;
kicad_of(el, "kicad", &mut inputs)?;
let id = ids.next().expect("each conductor has an id");
s.add(CONDUCTOR, inputs, Some(&id), Some("Via"), meta(el))?;
}
"wire" => {
refuse_unknown(el, &["name", "from", "to", "material", "points", "slack", "net"])?;
let pin = |key: &str| -> Result<Json, String> {
let sel = el.attr_of(key).cloned().unwrap_or(Json::Null);
let t = end(&sel, el, 0)?;
match (t.get("ref"), t.get("number")) {
(Some(r), Some(n)) => Ok(Json::obj().with("ref", r.clone()).with("number", n.clone())),
_ => Err(format!("{}: a wire is soldered to a pin (\".R1 > .pin2\"), not {}", at(el), sel.text())),
}
};
let mut inputs = vec![("from".to_string(), pin("from")?), ("to".to_string(), pin("to")?)];
if let Some(m) = text_of(el, "material", false)? {
inputs.push(("material".into(), m.into()));
}
match el.attr_of("points") {
None => {}
Some(Json::Arr(pts)) if pts.len() >= 2 && pts.iter().all(|p| matches!(p, Json::Arr(q) if q.len() == 3 && q.iter().all(|v| v.as_f64().is_some_and(f64::is_finite)))) => {
inputs.push(("points".into(), Json::Arr(pts.clone())));
}
Some(_) => return Err(format!("{}: points is the wire's shape, [[x, y, z], …] in mm (two or more)", at(el))),
}
if let Some(slack) = num(el, "slack", false)? {
if slack < 0.0 {
return Err(format!("{}: slack is 0 or more", at(el)));
}
inputs.push(("slack".into(), slack.into()));
}
net_of(el, &mut inputs)?;
let id = match el.attr_of("name").and_then(Json::as_str) {
Some(n) => n.to_string(),
None => format!("wire_{}", children.iter().filter(|c| c.tag == "wire").position(|c| std::ptr::eq(*c, el)).unwrap_or_default() + 1),
};
s.add(BOARD_WIRE, inputs, Some(&id), Some("Wire"), meta(el))?;
}
"pour" => {
refuse_unknown(el, &["name", "layers", "points", "terminals", "net", "uuid", "kicad"])?;
let pts = point_list(el, "points", 3, None)?;
let raw: Vec<Json> = match el.attr_of("terminals") {
None => Vec::new(),
Some(Json::Arr(list))
if list.iter().all(|t| matches!(t, Json::Arr(p) if p.len() == 2 && p[0].as_f64().is_some_and(|n| n.is_finite() && n.fract() == 0.0) && p[1].as_str().is_some())) =>
{
list.clone()
}
Some(_) => return Err(format!("{}: terminals is a list of [point, selector] ([[0, \".J1 > .pin2\"], …])", at(el))),
};
let mut terminals = Vec::new();
for t in &raw {
let Json::Arr(p) = t else { continue };
let point = p[0].as_f64().unwrap_or_default();
if point < 0.0 || point >= pts.len() as f64 {
return Err(format!("{}: the pour has no point {}", at(el), p[0].text()));
}
terminals.push(end(&p[1], el, point as usize)?);
}
let mut inputs = vec![
("kind".to_string(), Json::from("pour")),
("points".into(), pts.iter().map(|(x, y)| xy(*x, *y)).collect::<Vec<_>>().into()),
("layers".into(), copper_layers(el, Some(&board_copper), None)?.into_iter().map(Json::from).collect::<Vec<_>>().into()),
];
if !terminals.is_empty() {
inputs.push(("terminals".into(), terminals.into()));
}
uuid_of(el, &mut inputs)?;
net_of(el, &mut inputs)?;
kicad_of(el, "kicad", &mut inputs)?;
let id = ids.next().expect("each conductor has an id");
s.add(CONDUCTOR, inputs, Some(&id), Some("Pour"), meta(el))?;
}
"graphic" => {
refuse_unknown(el, &["kind", "layer", "points", "width", "filled", "arcs", "id", "kicad"])?;
let kind = text_of(el, "kind", true)?.unwrap_or_default();
let Some((_, count)) = GRAPHICS.iter().find(|(k, _)| *k == kind) else {
let kinds: Vec<&str> = GRAPHICS.iter().map(|(k, _)| *k).collect();
return Err(format!("{}: kind is {}", at(el), kinds.join(", ")));
};
let filled = match el.attr_of("filled") {
None => None,
Some(Json::Bool(b)) => Some(*b),
Some(_) => return Err(format!("{}: filled is true or false", at(el))),
};
let open = kind == "line" || kind == "arc";
if filled.is_some() && open {
return Err(format!("{}: a {kind} is not filled", at(el)));
}
let mut inputs = vec![("fact".to_string(), Json::from("graphic"))];
if el.attr_of("id").is_some() {
inputs.push(("id".into(), text_of(el, "id", false)?.unwrap_or_default().into()));
}
inputs.push(("kind".into(), kind.as_str().into()));
let least = if kind == "poly" { 2 } else { count.unwrap_or(2) };
let corners = point_list(el, "points", least, *count)?;
inputs.push(("points".into(), corners.iter().map(|(x, y)| xy(*x, *y)).collect::<Vec<_>>().into()));
if let Some(arcs) = el.attr_of("arcs") {
let mut next = 0usize;
let starts: Option<Vec<usize>> = match arcs {
Json::Arr(list) if kind == "poly" && !list.is_empty() => list
.iter()
.map(|v| match v {
Json::Num(n) if n.fract() == 0.0 && *n >= next as f64 && (*n as usize) + 3 <= corners.len() => {
next = *n as usize + 3;
Some(*n as usize)
}
_ => None,
})
.collect(),
_ => None,
};
if starts.is_none() {
return Err(format!("{}: arcs is, on a poly, the increasing indices in points where an arc's start, mid and end begin (3 points each, not overlapping)", at(el)));
}
inputs.push(("arcStarts".into(), arcs.clone()));
}
inputs.push(("widthMm".into(), num(el, "width", true)?.unwrap_or_default().into()));
inputs.push(("layer".into(), text_of(el, "layer", true)?.unwrap_or_default().into()));
if !open {
inputs.push(("filled".into(), filled.unwrap_or(false).into()));
}
kicad_of(el, "kicad", &mut inputs)?;
s.add(BOARD_FACT, inputs, None, Some("Graphic"), meta(el))?;
}
"text" => {
refuse_unknown(el, &["text", "field", "at", "rotation", "layer", "size", "sizeX", "thickness", "kind", "id", "kicad"])?;
let (t, field) = (text_of(el, "text", false)?, text_of(el, "field", false)?);
if t.is_none() == field.is_none() {
return Err("text(): give text, or field (\"reference\" or \"value\")".into());
}
if field.as_ref().is_some_and(|f| f != "reference" && f != "value") {
return Err("text(): field is \"reference\" or \"value\"".into());
}
let mut inputs = vec![("fact".to_string(), Json::from("text"))];
if el.attr_of("id").is_some() {
inputs.push(("id".into(), text_of(el, "id", false)?.unwrap_or_default().into()));
}
match (t, field) {
(Some(t), _) => inputs.push(("text".into(), t.into())),
(None, Some(f)) => inputs.push(("field".into(), f.into())),
(None, None) => {}
}
inputs.push(("at".into(), at_point(el, "at")?));
inputs.push(("rot".into(), num(el, "rotation", false)?.unwrap_or(0.0).into()));
inputs.push(("layer".into(), text_of(el, "layer", true)?.unwrap_or_default().into()));
let size = num(el, "size", true)?.unwrap_or_default();
inputs.push(("size".into(), size.into()));
inputs.push(("sizeX".into(), num(el, "sizeX", false)?.unwrap_or(size).into()));
inputs.push(("thickness".into(), num(el, "thickness", true)?.unwrap_or_default().into()));
inputs.push(("kind".into(), text_of(el, "kind", false)?.unwrap_or_else(|| "text".into()).into()));
kicad_of(el, "kicad", &mut inputs)?;
s.add(BOARD_FACT, inputs, None, Some("Text"), meta(el))?;
}
"dimension" => {
refuse_unknown(el, &["points", "height", "layer", "width", "textSize", "id", "kicad"])?;
let mut inputs = vec![
("fact".to_string(), Json::from("dimension")),
("id".into(), text_of(el, "id", false)?.unwrap_or_default().into()),
("points".into(), point_list(el, "points", 2, Some(2))?.iter().map(|(x, y)| xy(*x, *y)).collect::<Vec<_>>().into()),
("height".into(), num(el, "height", true)?.unwrap_or_default().into()),
("layer".into(), text_of(el, "layer", true)?.unwrap_or_default().into()),
("widthMm".into(), num(el, "width", true)?.unwrap_or_default().into()),
("textSize".into(), num(el, "textSize", true)?.unwrap_or_default().into()),
];
kicad_of(el, "kicad", &mut inputs)?;
s.add(BOARD_FACT, inputs, None, Some("Dimension"), meta(el))?;
}
"kicad" => {
refuse_unknown(el, &["version", "generator", "forms"])?;
let mut inputs = vec![("fact".to_string(), Json::from("kicad"))];
if let Some(v) = num(el, "version", false)? {
inputs.push(("version".into(), v.into()));
}
if let Some(g) = text_of(el, "generator", false)? {
inputs.push(("generator".into(), g.into()));
}
kicad_of(el, "forms", &mut inputs)?;
s.add(BOARD_FACT, inputs, None, Some("KiCad"), meta(el))?;
}
"net" => {
refuse_unknown(el, &["name", "code"])?;
let code = num(el, "code", true)?.unwrap_or_default();
if code.fract() != 0.0 || code < 0.0 {
return Err(format!("{}: code is a KiCad net code (0 or more)", at(el)));
}
let name = el.attr_of("name").cloned().unwrap_or(Json::Null);
let inputs = vec![("fact".to_string(), Json::from("net")), ("name".into(), name), ("code".into(), code.into())];
s.add(BOARD_FACT, inputs, None, Some("Net"), meta(el))?;
}
"fab" => {
s.add(BOARD_FACT, fab_fact(el)?, None, Some("Fab"), meta(el))?;
}
tag if CONSTRAINTS.contains(&tag) => {
s.add(BOARD_FACT, constraint_fact(el)?, None, Some(tag), meta(el))?;
}
_ => {}
}
}
Ok(has_board)
}