Skip to main content
← Back to kicad-monkey Rust Docs kicad-monkey Rust Crate API Reference

kicad_monkey_core/pcb/
setup.rs

1//! Source-backed board setup and physical stackup records.
2
3use super::*;
4
5#[derive(Clone, Debug, PartialEq)]
6pub struct PcbSetup {
7    /// Direct declaration presence, independent of the effective origin value.
8    pub has_aux_axis_origin: bool,
9    pub aux_axis_origin: PcbPoint,
10    /// Distinguishes an authored zero origin from the absent-origin default.
11    pub has_grid_origin: bool,
12    pub grid_origin: PcbPoint,
13    pub allow_soldermask_bridges_in_footprints: bool,
14    pub tenting_front: bool,
15    pub tenting_back: bool,
16    pub covering_front: bool,
17    pub covering_back: bool,
18    pub plugging_front: bool,
19    pub plugging_back: bool,
20    pub capping: bool,
21    pub filling: bool,
22    pub stackup: Option<PcbStackup>,
23    pub source_range: Range<usize>,
24}
25
26#[derive(Clone, Debug, PartialEq)]
27pub struct PcbStackup {
28    pub layers: Vec<PcbStackupLayer>,
29    pub copper_finish: String,
30    pub dielectric_constraints: bool,
31    pub edge_connector: String,
32    pub edge_plating: bool,
33    pub source_range: Range<usize>,
34}
35
36#[derive(Clone, Debug, PartialEq)]
37pub struct PcbStackupLayer {
38    pub name: String,
39    pub type_name: String,
40    /// Direct declaration presence, independent of the effective thickness.
41    pub has_thickness: bool,
42    pub thickness: f64,
43    pub thickness_locked: bool,
44    pub material: String,
45    pub epsilon_r: Option<f64>,
46    pub loss_tangent: Option<f64>,
47    pub color: String,
48    /// Additional ordered parameter groups introduced by bare `addsublayer`.
49    pub sublayers: Vec<PcbStackupSubLayer>,
50    pub source_range: Range<usize>,
51}
52
53#[derive(Clone, Debug, PartialEq)]
54pub struct PcbStackupSubLayer {
55    pub has_thickness: bool,
56    pub thickness: f64,
57    pub thickness_locked: bool,
58    pub material: String,
59    pub epsilon_r: Option<f64>,
60    pub loss_tangent: Option<f64>,
61    pub color: String,
62    /// Parameter group bytes, including its bare separator when present.
63    pub source_range: Range<usize>,
64}
65
66impl<'a> PcbView<'a> {
67    /// Authored setup tenting flags; absence differs from an explicit `no`.
68    /// Existing effective setup defaults remain available through `setup`.
69    pub fn setup_tenting(&self) -> Result<Option<PcbFrontBackOptionalBool>, Error> {
70        if !self.selection.contains(PcbFamily::Setup) {
71            return Err(Error::build(
72                ErrorKind::UnexpectedToken,
73                "setup tenting requires setup source family",
74            ));
75        }
76        let Some(span) = self.first_top_level("setup") else {
77            return Ok(None);
78        };
79        let children = direct_children(
80            self.source,
81            span,
82            self.limits.max_setup_children,
83            self.limits,
84        )?;
85        let declarations = children
86            .iter()
87            .filter(|row| row.head.as_deref() == Some("tenting"))
88            .collect::<Vec<_>>();
89        let mut names = Vec::new();
90        // Malformed declared policy is fatal before duplicate capability refusal.
91        for tenting in &declarations {
92            let flags =
93                bounded_scalar_values(self.source, tenting, self.limits.max_via_policy_children)?;
94            for token in flags {
95                if token.kind != TokenKind::Atom || !matches!(token.lexeme, "front" | "back") {
96                    return Err(Error::at(
97                        ErrorPhase::Tree,
98                        ErrorKind::InvalidBuildValue,
99                        "setup tenting requires exact front/back side flags",
100                        tenting.start,
101                    ));
102                }
103                names.push(token.lexeme.to_owned());
104            }
105            for leaf in direct_children(
106                self.source,
107                tenting,
108                self.limits.max_via_policy_children,
109                self.limits,
110            )? {
111                let values =
112                    bounded_scalar_values(self.source, &leaf, self.limits.max_via_policy_children)?;
113                if !matches!(leaf.head.as_deref(), Some("front" | "back"))
114                    || values.len() != 1
115                    || values[0].kind != TokenKind::Atom
116                    || !matches!(values[0].lexeme, "yes" | "no" | "none")
117                    || !direct_children(
118                        self.source,
119                        &leaf,
120                        self.limits.max_via_policy_children,
121                        self.limits,
122                    )?
123                    .is_empty()
124                {
125                    return Err(Error::at(
126                        ErrorPhase::Tree,
127                        ErrorKind::InvalidBuildValue,
128                        "setup tenting requires exact front/back yes/no/none leaves",
129                        leaf.start,
130                    ));
131                }
132                names.push(leaf.head.clone().unwrap());
133            }
134        }
135        let unique = names.iter().collect::<std::collections::HashSet<_>>();
136        if declarations.len() > 1 || unique.len() != names.len() {
137            return Err(Error::build(
138                ErrorKind::UnexpectedToken,
139                "duplicate or mixed setup tenting declarations are not qualified",
140            ));
141        }
142        let pair = vias::front_back_optional_bool(self.source, &children, "tenting", self.limits)?;
143        let Some(tenting) = declarations.first() else {
144            return Ok(None);
145        };
146        let flags =
147            bounded_scalar_values(self.source, tenting, self.limits.max_via_policy_children)?;
148        let front = if has_flag(&flags, "front") {
149            Some(true)
150        } else {
151            pair.as_ref().and_then(|row| row.front)
152        };
153        let back = if has_flag(&flags, "back") {
154            Some(true)
155        } else {
156            pair.as_ref().and_then(|row| row.back)
157        };
158        Ok(
159            (front.is_some() || back.is_some()).then(|| PcbFrontBackOptionalBool {
160                front,
161                back,
162                source_range: tenting.range.clone(),
163            }),
164        )
165    }
166
167    /// Effective KiCad auxiliary datum in CAD coordinates, including the zero default.
168    /// An absent declaration/setup does not become authored evidence.
169    pub fn effective_auxiliary_origin(&self) -> Result<PcbPoint, Error> {
170        if !self.selection.contains(PcbFamily::Setup) {
171            return Err(Error::build(
172                ErrorKind::InvalidBuildValue,
173                "Effective auxiliary origin requires the selected setup family",
174            ));
175        }
176        let Some(setup) = self.first_top_level("setup") else {
177            return Ok(PcbPoint { x: 0.0, y: 0.0 });
178        };
179        let children = direct_children(
180            self.source,
181            setup,
182            self.limits.max_setup_children,
183            self.limits,
184        )?;
185        let Some(declaration) = child(&children, "aux_axis_origin") else {
186            return Ok(PcbPoint { x: 0.0, y: 0.0 });
187        };
188        let [x, y] = exact_finite_values(
189            self.source,
190            declaration,
191            self.limits,
192            "aux_axis_origin requires exactly two finite numeric coordinates",
193        )?;
194        Ok(PcbPoint { x, y })
195    }
196
197    pub fn setup(&self) -> Result<Option<PcbSetup>, Error> {
198        if !self.selection.contains(PcbFamily::Setup) {
199            return Ok(None);
200        }
201        self.first_top_level("setup")
202            .map(|span| setup_from_span(self.source, span, self.limits))
203            .transpose()
204    }
205
206    /// The authored setup, or KiCad's defaults when the board has no `(setup)`
207    /// form: pcbnew loads such a board with its default design settings.
208    pub fn effective_setup(&self) -> Result<PcbSetup, Error> {
209        if !self.selection.contains(PcbFamily::Setup) {
210            return Err(Error::build(
211                ErrorKind::InvalidBuildValue,
212                "effective setup requires the selected setup family",
213            ));
214        }
215        Ok(self.setup()?.unwrap_or_else(PcbSetup::kicad_default))
216    }
217
218    /// The declared board layers, or KiCad's default board layers when the
219    /// file has no `(layers)` form, as pcbnew loads and saves such a board.
220    /// Default rows have an empty source range.
221    pub fn effective_layers(&self) -> Result<Vec<PcbLayer>, Error> {
222        if !self.selection.contains(PcbFamily::Layers) || self.first_top_level("layers").is_some() {
223            return self.layers().collect();
224        }
225        Ok(KICAD_DEFAULT_BOARD_LAYERS
226            .iter()
227            .map(|&(ordinal, name, kind, user_name)| PcbLayer {
228                ordinal,
229                name: name.into(),
230                kind: kind.into(),
231                user_name: user_name.map(Into::into),
232                source_range: 0..0,
233            })
234            .collect())
235    }
236}
237
238/// KiCad's board layers for a file that declares none: what kicad-cli 10.0.5
239/// `pcb upgrade` writes for a board with no `(layers)` form, as
240/// (ordinal, name, type, user name).
241const KICAD_DEFAULT_BOARD_LAYERS: &[(i64, &str, &str, Option<&str>)] = &[
242    (0, "F.Cu", "signal", None),
243    (2, "B.Cu", "signal", None),
244    (9, "F.Adhes", "user", Some("F.Adhesive")),
245    (11, "B.Adhes", "user", Some("B.Adhesive")),
246    (13, "F.Paste", "user", None),
247    (15, "B.Paste", "user", None),
248    (5, "F.SilkS", "user", Some("F.Silkscreen")),
249    (7, "B.SilkS", "user", Some("B.Silkscreen")),
250    (1, "F.Mask", "user", None),
251    (3, "B.Mask", "user", None),
252    (17, "Dwgs.User", "user", Some("User.Drawings")),
253    (19, "Cmts.User", "user", Some("User.Comments")),
254    (21, "Eco1.User", "user", Some("User.Eco1")),
255    (23, "Eco2.User", "user", Some("User.Eco2")),
256    (25, "Edge.Cuts", "user", None),
257    (27, "Margin", "user", None),
258    (31, "F.CrtYd", "user", Some("F.Courtyard")),
259    (29, "B.CrtYd", "user", Some("B.Courtyard")),
260    (35, "F.Fab", "user", None),
261    (33, "B.Fab", "user", None),
262    (39, "User.1", "user", None),
263    (41, "User.2", "user", None),
264    (43, "User.3", "user", None),
265    (45, "User.4", "user", None),
266];
267
268impl PcbSetup {
269    /// KiCad's design settings for a board with no `(setup)` form, as
270    /// kicad-cli 10.0.5 `pcb upgrade` writes them: vias tented on both sides,
271    /// no covering, plugging, capping or filling, no origins and no stackup.
272    pub fn kicad_default() -> Self {
273        Self {
274            has_aux_axis_origin: false,
275            aux_axis_origin: PcbPoint { x: 0.0, y: 0.0 },
276            has_grid_origin: false,
277            grid_origin: PcbPoint { x: 0.0, y: 0.0 },
278            allow_soldermask_bridges_in_footprints: false,
279            tenting_front: true,
280            tenting_back: true,
281            covering_front: false,
282            covering_back: false,
283            plugging_front: false,
284            plugging_back: false,
285            capping: false,
286            filling: false,
287            stackup: None,
288            source_range: 0..0,
289        }
290    }
291}
292
293fn setup_from_span(source: &str, span: &FormSpan, limits: PcbLimits) -> Result<PcbSetup, Error> {
294    let children = direct_children(source, span, limits.max_setup_children, limits)?;
295    let aux = optional_pair(source, &children, "aux_axis_origin", [0.0, 0.0])?;
296    let grid = grid_origin_from_declarations(source, &children, limits)?;
297    Ok(PcbSetup {
298        has_aux_axis_origin: child(&children, "aux_axis_origin").is_some(),
299        aux_axis_origin: PcbPoint {
300            x: aux[0],
301            y: aux[1],
302        },
303        has_grid_origin: child(&children, "grid_origin").is_some(),
304        grid_origin: PcbPoint {
305            x: grid[0],
306            y: grid[1],
307        },
308        allow_soldermask_bridges_in_footprints: child_bool(
309            source,
310            &children,
311            "allow_soldermask_bridges_in_footprints",
312        )?,
313        tenting_front: tenting_side(source, &children, "front", limits)?,
314        tenting_back: tenting_side(source, &children, "back", limits)?,
315        covering_front: side_enabled(source, &children, "covering", "front", limits)?,
316        covering_back: side_enabled(source, &children, "covering", "back", limits)?,
317        plugging_front: side_enabled(source, &children, "plugging", "front", limits)?,
318        plugging_back: side_enabled(source, &children, "plugging", "back", limits)?,
319        capping: child_bool(source, &children, "capping")?,
320        filling: child_bool(source, &children, "filling")?,
321        stackup: child(&children, "stackup")
322            .map(|stackup| stackup_from_span(source, stackup, limits))
323            .transpose()?,
324        source_range: span.range.clone(),
325    })
326}
327
328// Pinned parsePCB_SETUP T_grid_origin reads two numbers, NeedRIGHT, then
329// SetGridOrigin. Preserve declaration order without altering generic pairs.
330fn grid_origin_from_declarations(
331    source: &str,
332    children: &[FormSpan],
333    limits: PcbLimits,
334) -> Result<[f64; 2], Error> {
335    let mut origin = [0.0, 0.0];
336    for declaration in children
337        .iter()
338        .filter(|row| row.head.as_deref() == Some("grid_origin"))
339    {
340        let values = bounded_scalar_values(source, declaration, limits.max_setup_children)?;
341        if values.len() != 2
342            || values
343                .iter()
344                .any(|value| !matches!(value.kind, TokenKind::Integer | TokenKind::Float))
345            || !direct_children(source, declaration, limits.max_setup_children, limits)?.is_empty()
346        {
347            return Err(source_error(
348                "grid_origin requires exactly two finite numeric coordinates",
349                declaration.start,
350            ));
351        }
352        for (index, token) in values.iter().enumerate() {
353            let value = required_f64(
354                Some(token),
355                "grid_origin requires a finite numeric coordinate",
356                declaration,
357            )?;
358            if !value.is_finite() {
359                return Err(source_error(
360                    "grid_origin requires a finite numeric coordinate",
361                    declaration.start,
362                ));
363            }
364            origin[index] = value;
365        }
366    }
367    Ok(origin)
368}
369
370/// A setup's via tenting on one side. A setup with no `(tenting)` (KiCad 8
371/// and older) tents both sides, as pcbnew loads it, unless its plot settings
372/// put vias on the mask (`(pcbplotparams (viasonmask yes))`, the legacy
373/// untented setting). Measured with kicad-cli 10.0.5 on nRF9151_Feather:
374/// `viasonmask no` or no such row opens no via; `viasonmask yes` opens all.
375fn tenting_side(
376    source: &str,
377    setup_children: &[FormSpan],
378    side: &str,
379    limits: PcbLimits,
380) -> Result<bool, Error> {
381    if child(setup_children, "tenting").is_some() {
382        return side_enabled(source, setup_children, "tenting", side, limits);
383    }
384    let Some(plot) = child(setup_children, "pcbplotparams") else {
385        return Ok(true);
386    };
387    let plot_children = direct_children(source, plot, limits.max_setup_children, limits)?;
388    Ok(!child_bool(source, &plot_children, "viasonmask")?)
389}
390
391fn side_enabled(
392    source: &str,
393    setup_children: &[FormSpan],
394    head: &str,
395    side: &str,
396    limits: PcbLimits,
397) -> Result<bool, Error> {
398    let Some(span) = child(setup_children, head) else {
399        return Ok(false);
400    };
401    let flags = bounded_scalar_values(source, span, 8)?;
402    if has_flag(&flags, side) {
403        return Ok(true);
404    }
405    let fields = direct_children(source, span, 8, limits)?;
406    child_bool(source, &fields, side)
407}
408
409fn stackup_from_span(
410    source: &str,
411    span: &FormSpan,
412    limits: PcbLimits,
413) -> Result<PcbStackup, Error> {
414    let children = direct_children(source, span, limits.max_setup_children, limits)?;
415    let mut layers = Vec::new();
416    for layer in children
417        .iter()
418        .filter(|child| child.head.as_deref() == Some("layer"))
419    {
420        if layers.len() == limits.max_stackup_layers {
421            return Err(limit_error());
422        }
423        layers.push(stackup_layer_from_span(source, layer, limits)?);
424    }
425    Ok(PcbStackup {
426        layers,
427        copper_finish: optional_child_string(source, &children, "copper_finish")?
428            .unwrap_or_default(),
429        dielectric_constraints: child_bool(source, &children, "dielectric_constraints")?,
430        edge_connector: optional_child_string(source, &children, "edge_connector")?
431            .unwrap_or_else(|| "none".to_owned()),
432        edge_plating: child_bool(source, &children, "edge_plating")?,
433        source_range: span.range.clone(),
434    })
435}
436
437fn stackup_layer_from_span(
438    source: &str,
439    span: &FormSpan,
440    limits: PcbLimits,
441) -> Result<PcbStackupLayer, Error> {
442    let name = first_string(source, span)?.unwrap_or_default();
443    let children = direct_children(source, span, 32, limits)?;
444    if children
445        .iter()
446        .any(|field| field.head.as_deref() == Some("addsublayer"))
447    {
448        return Err(source_error(
449            "Expected bare stackup addsublayer separator",
450            span.start,
451        ));
452    }
453    // Both scalars and child forms are bounded before allocating parameter groups.
454    let scalars = bounded_scalar_values(source, span, 32)?;
455    let mut boundaries = vec![span.range.start];
456    boundaries.extend(
457        scalars
458            .iter()
459            .skip(1)
460            .filter(|token| token.kind == TokenKind::Atom && token.lexeme == "addsublayer")
461            .map(|token| span.range.start + token.position.offset),
462    );
463    boundaries.push(span.range.end - 1);
464    let mut groups = boundaries.windows(2).map(|range| {
465        let fields = children
466            .iter()
467            .filter(|field| field.range.start >= range[0] && field.range.end <= range[1])
468            .cloned()
469            .collect::<Vec<_>>();
470        stackup_parameters(source, &fields, range[0]..range[1])
471    });
472    let main = groups.next().expect("main stackup parameter group")?;
473    let sublayers = groups.collect::<Result<Vec<_>, _>>()?;
474    Ok(PcbStackupLayer {
475        name,
476        type_name: optional_child_string(source, &children, "type")?.unwrap_or_default(),
477        has_thickness: main.has_thickness,
478        thickness: main.thickness,
479        thickness_locked: main.thickness_locked,
480        material: main.material,
481        epsilon_r: main.epsilon_r,
482        loss_tangent: main.loss_tangent,
483        color: main.color,
484        sublayers,
485        source_range: span.range.clone(),
486    })
487}
488
489fn stackup_parameters(
490    source: &str,
491    children: &[FormSpan],
492    source_range: Range<usize>,
493) -> Result<PcbStackupSubLayer, Error> {
494    let thickness = child(children, "thickness");
495    let thickness_flags = thickness
496        .map(|value| bounded_scalar_values(source, value, 8))
497        .transpose()?
498        .unwrap_or_default();
499    Ok(PcbStackupSubLayer {
500        has_thickness: thickness.is_some(),
501        thickness: match thickness {
502            Some(declaration) => required_f64(
503                thickness_flags.first(),
504                "Expected stackup thickness value",
505                declaration,
506            )?,
507            None => 0.0,
508        },
509        thickness_locked: has_flag(&thickness_flags, "locked"),
510        material: optional_child_string(source, children, "material")?.unwrap_or_default(),
511        epsilon_r: optional_child_f64(source, children, "epsilon_r")?,
512        loss_tangent: optional_child_f64(source, children, "loss_tangent")?,
513        color: optional_child_string(source, children, "color")?.unwrap_or_default(),
514        source_range,
515    })
516}