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

kicad_monkey_core/
plotter_ir.rs

1//! Shared plotter operations and the source-selected footprint producer.
2
3use crate::footprint::{FootprintLimits, FootprintView};
4use crate::footprint_plotter_text::footprint_text_operations;
5pub use crate::plotter_types::*;
6use crate::sexpr::{Error, ErrorKind, ErrorPhase, Lexer, Position, Sexp, TokenKind, parse};
7use crate::sexpr_projection::{FormSpan, Selector};
8use std::ops::Range;
9const DEFAULT_FOOTPRINT_VERSION: i64 = 20_260_206;
10const DEFAULT_GENERATOR: &str = "pcbnew";
11const DEFAULT_GENERATOR_VERSION: &str = "10.0";
12const DEFAULT_FOOTPRINT_LAYER: &str = "F.Cu";
13const DEFAULT_LINE_LAYER: &str = "F.SilkS";
14const DEFAULT_STROKE_WIDTH_NM: i64 = 152_400;
15const MIN_PLOT_PEN_WIDTH_NM: i64 = 84_700;
16const JAVASCRIPT_SAFE_INTEGER_MAX: i64 = 9_007_199_254_740_991;
17const JAVASCRIPT_SAFE_INTEGER_MIN: i64 = -JAVASCRIPT_SAFE_INTEGER_MAX;
18const DASH_RATIO: f64 = 11.0;
19const GAP_RATIO: f64 = 4.0;
20const DOT_RATIO: f64 = 0.2;
21const ARC_CHORD_STEP_RADIANS: f64 = std::f64::consts::PI / 360.0;
22const MAX_DECOMPOSITION_STEPS: usize = 10_000;
23
24/// Ignored ceilings, defaulting to `usize::MAX`: KiCad reads and plots boards
25/// and footprints without them (#612). Request hosts still pass caller values.
26#[derive(Clone, Copy, Debug, Eq, PartialEq)]
27pub struct FootprintPlotLimits {
28    pub max_source_bytes: usize,
29    pub max_depth: usize,
30    pub max_metadata_forms: usize,
31    pub max_text_carriers: usize,
32    pub max_text_bytes: usize,
33    pub max_operations: usize,
34    pub max_points: usize,
35}
36
37impl Default for FootprintPlotLimits {
38    fn default() -> Self {
39        Self {
40            max_source_bytes: usize::MAX,
41            max_depth: usize::MAX,
42            max_metadata_forms: usize::MAX,
43            max_text_carriers: usize::MAX,
44            max_text_bytes: usize::MAX,
45            max_operations: usize::MAX,
46            max_points: usize::MAX,
47        }
48    }
49}
50
51/// Typed facts needed to serialize the promoted footprint plotter subset.
52#[derive(Clone, Debug, PartialEq)]
53pub struct FootprintPlotDocument {
54    pub name: String,
55    pub version: i64,
56    pub generator: String,
57    pub generator_version: String,
58    pub layer: String,
59    pub uuid: String,
60    pub descr: String,
61    pub tags: String,
62    pub attr: Vec<String>,
63    pub locked: bool,
64    pub placed: bool,
65    pub operations: Vec<PlotterOperation>,
66}
67
68#[derive(Default)]
69struct FootprintGeometrySpans {
70    lines: Vec<FormSpan>,
71    arcs: Vec<FormSpan>,
72    circles: Vec<FormSpan>,
73    rects: Vec<FormSpan>,
74    polys: Vec<FormSpan>,
75    pads: Vec<FormSpan>,
76}
77
78/// Read supported footprint geometry directly from selected forms.
79#[allow(
80    clippy::cognitive_complexity,
81    clippy::too_many_lines,
82    reason = "pre-standard source-selection orchestrator retained under the structural ratchet"
83)]
84pub fn footprint_plot_document(
85    source: &str,
86    limits: FootprintPlotLimits,
87) -> Result<FootprintPlotDocument, Error> {
88    footprint_plot_document_internal(source, limits, None)
89}
90
91/// Return the ordinary document plus source-only primary capability errors.
92pub fn footprint_plot_document_with_primary_errors(
93    source: &str,
94    limits: FootprintPlotLimits,
95) -> Result<(FootprintPlotDocument, Vec<Error>), Error> {
96    let mut errors = Vec::new();
97    let document = footprint_plot_document_internal(source, limits, Some(&mut errors))?;
98    Ok((document, errors))
99}
100
101#[allow(
102    clippy::too_many_lines,
103    reason = "footprint Plotter-IR builder assembles graphics, pads, texts, and zones in one pass"
104)]
105fn footprint_plot_document_internal(
106    source: &str,
107    limits: FootprintPlotLimits,
108    primary_errors: Option<&mut Vec<Error>>,
109) -> Result<FootprintPlotDocument, Error> {
110    let footprint_limits = FootprintLimits {
111        max_source_bytes: limits.max_source_bytes,
112        max_depth: limits.max_depth,
113        max_properties: limits.max_text_carriers,
114        max_texts: limits.max_text_carriers,
115        max_text_boxes: limits.max_text_carriers,
116        max_text_carriers: limits.max_text_carriers,
117        ..FootprintLimits::default()
118    };
119    let view = FootprintView::parse(source, footprint_limits)?;
120    let name = view.name()?.into_owned();
121    let paths = [
122        "version",
123        "generator",
124        "generator_version",
125        "layer",
126        "uuid",
127        "descr",
128        "tags",
129        "attr",
130        "solder_mask_margin",
131        "fp_line",
132        "fp_arc",
133        "fp_circle",
134        "fp_rect",
135        "fp_poly",
136        "pad",
137    ]
138    .into_iter()
139    .map(|head| vec!["footprint".to_owned(), head.to_owned()])
140    .collect();
141    let spans = crate::sexpr_projection::scan_form_spans(
142        source,
143        &Selector {
144            paths: Some(paths),
145            min_depth: Some(1),
146            max_depth: Some(1),
147            ..Selector::default()
148        },
149    )?;
150
151    let mut version = None;
152    let mut generator = None;
153    let mut generator_version = None;
154    let mut layer = None;
155    let mut uuid = None;
156    let mut descr = None;
157    let mut tags = None;
158    let mut attr = None;
159    let mut solder_mask_margin = None;
160    let mut metadata_forms = 0usize;
161    let mut geometry = FootprintGeometrySpans::default();
162    for span in spans {
163        if !matches!(
164            span.head.as_deref(),
165            Some("fp_line" | "fp_arc" | "fp_circle" | "fp_rect" | "fp_poly" | "pad")
166        ) {
167            metadata_forms = metadata_forms.saturating_add(1);
168            if metadata_forms > limits.max_metadata_forms {
169                return Err(metadata_limit_error());
170            }
171        }
172        match span.head.as_deref() {
173            Some("version") if version.is_none() => {
174                version = Some(form_integer(source, &span, "version")?);
175            }
176            Some("generator") if generator.is_none() => {
177                generator = Some(form_string(source, &span, "generator")?);
178            }
179            Some("generator_version") if generator_version.is_none() => {
180                generator_version = Some(form_string(source, &span, "generator_version")?);
181            }
182            Some("layer") if layer.is_none() => {
183                layer = Some(form_string(source, &span, "layer")?);
184            }
185            Some("uuid") if uuid.is_none() => {
186                uuid = Some(form_string(source, &span, "uuid")?);
187            }
188            Some("descr") if descr.is_none() => {
189                descr = Some(form_string(source, &span, "descr")?);
190            }
191            Some("tags") if tags.is_none() => {
192                tags = Some(form_string(source, &span, "tags")?);
193            }
194            Some("attr") if attr.is_none() => {
195                attr = Some(form_strings(source, &span, "attr")?);
196            }
197            Some("solder_mask_margin") if solder_mask_margin.is_none() => {
198                solder_mask_margin = Some(form_number(source, &span, "solder_mask_margin")?);
199            }
200            Some("fp_line") => geometry.lines.push(span),
201            Some("fp_arc") => geometry.arcs.push(span),
202            Some("fp_circle") => geometry.circles.push(span),
203            Some("fp_rect") => geometry.rects.push(span),
204            Some("fp_poly") => geometry.polys.push(span),
205            Some("pad") => geometry.pads.push(span),
206            _ => {}
207        }
208    }
209    let text_operations = footprint_text_operations(&view, limits, primary_errors)?;
210    let operations = build_geometry_operations(
211        source,
212        geometry,
213        solder_mask_margin.unwrap_or(0.0),
214        text_operations,
215        limits,
216    )?;
217    let (locked, placed) = root_flags(source)?;
218    let version = version.unwrap_or(DEFAULT_FOOTPRINT_VERSION);
219    ensure_javascript_safe_integer(version)?;
220    Ok(FootprintPlotDocument {
221        name,
222        version,
223        generator: generator.unwrap_or_else(|| DEFAULT_GENERATOR.to_owned()),
224        generator_version: generator_version
225            .unwrap_or_else(|| DEFAULT_GENERATOR_VERSION.to_owned()),
226        layer: layer.unwrap_or_else(|| DEFAULT_FOOTPRINT_LAYER.to_owned()),
227        uuid: uuid.unwrap_or_default(),
228        descr: descr.unwrap_or_default(),
229        tags: tags.unwrap_or_default(),
230        attr: attr.unwrap_or_default(),
231        locked,
232        placed,
233        operations,
234    })
235}
236
237fn build_geometry_operations(
238    source: &str,
239    geometry: FootprintGeometrySpans,
240    footprint_mask_margin: f64,
241    mut operations: Vec<PlotterOperation>,
242    limits: FootprintPlotLimits,
243) -> Result<Vec<PlotterOperation>, Error> {
244    let mut point_count = 0usize;
245    for span in geometry.lines {
246        let remaining = remaining_operations(&operations, limits)?;
247        let additions = parse_line(source, &span, remaining)?;
248        append_bounded_operations(&mut operations, additions, limits, &mut point_count)?;
249    }
250    for span in geometry.arcs {
251        let remaining = remaining_operations(&operations, limits)?;
252        let additions = parse_arc(source, &span, remaining)?;
253        append_bounded_operations(&mut operations, additions, limits, &mut point_count)?;
254    }
255    for span in geometry.circles {
256        append_bounded_operations(
257            &mut operations,
258            vec![parse_circle(source, &span)?],
259            limits,
260            &mut point_count,
261        )?;
262    }
263    for span in geometry.rects {
264        append_bounded_operations(
265            &mut operations,
266            vec![parse_rect(source, &span)?],
267            limits,
268            &mut point_count,
269        )?;
270    }
271    for span in geometry.polys {
272        let remaining_points = limits.max_points.saturating_sub(point_count);
273        append_bounded_operations(
274            &mut operations,
275            vec![parse_poly(source, &span, remaining_points)?],
276            limits,
277            &mut point_count,
278        )?;
279    }
280    for span in geometry.pads {
281        let remaining = limits.max_operations.saturating_sub(operations.len());
282        let remaining_points = limits.max_points.saturating_sub(point_count);
283        let additions = parse_pad(
284            source,
285            &span,
286            footprint_mask_margin,
287            0.0,
288            remaining,
289            remaining_points,
290        )?
291        .into_operations();
292        append_bounded_operations(&mut operations, additions, limits, &mut point_count)?;
293    }
294    Ok(operations)
295}
296
297/// Footprint graphic conversion shared by standalone and board-embedded
298/// producers. The source range is already bounded and owned by a typed PCB
299/// view; reparsing just the selected form avoids rebuilding a second tree.
300pub(crate) fn footprint_graphic_operations_from_range(
301    source: &str,
302    range: Range<usize>,
303    head: &str,
304    max_operations: usize,
305    max_points: usize,
306    max_depth: usize,
307    max_nodes: usize,
308) -> Result<Vec<PlotterOperation>, Error> {
309    validate_selected_form(source, range.clone(), max_depth, max_nodes)?;
310    let span = selected_form_span(range, head);
311    match head {
312        "fp_line" => parse_line(source, &span, max_operations),
313        "fp_arc" => parse_arc(source, &span, max_operations),
314        "fp_circle" => Ok(vec![parse_circle(source, &span)?]),
315        "fp_rect" => Ok(vec![parse_rect(source, &span)?]),
316        "fp_poly" => Ok(vec![parse_poly(source, &span, max_points)?]),
317        _ => Err(model_error(
318            "Unsupported footprint graphic",
319            Position::START,
320        )),
321    }
322}
323
324#[derive(Debug, Default)]
325pub(crate) struct FootprintPadOperations {
326    pub flash: Vec<PlotterOperation>,
327    pub drill: Vec<PlotterOperation>,
328}
329
330#[derive(Clone, Copy)]
331pub(crate) struct FootprintPadParseLimits {
332    pub max_operations: usize,
333    pub max_points: usize,
334    pub max_depth: usize,
335    pub max_nodes: usize,
336}
337
338impl FootprintPadOperations {
339    fn into_operations(mut self) -> Vec<PlotterOperation> {
340        self.flash.append(&mut self.drill);
341        self.flash
342    }
343}
344
345/// Pad conversion shared by standalone and board-embedded footprint
346/// producers. Embedded footprints pass the negative placement angle so pad
347/// flashes retain Python's footprint-local orientation convention.
348pub(crate) fn footprint_pad_operations_from_range(
349    source: &str,
350    range: Range<usize>,
351    footprint_mask_margin_mm: f64,
352    orient_deg_offset: f64,
353    limits: FootprintPadParseLimits,
354) -> Result<FootprintPadOperations, Error> {
355    validate_selected_form(source, range.clone(), limits.max_depth, limits.max_nodes)?;
356    parse_pad(
357        source,
358        &selected_form_span(range, "pad"),
359        footprint_mask_margin_mm,
360        orient_deg_offset,
361        limits.max_operations,
362        limits.max_points,
363    )
364}
365
366fn validate_selected_form(
367    source: &str,
368    range: Range<usize>,
369    _max_depth: usize,
370    _max_nodes: usize,
371) -> Result<(), Error> {
372    let selected = source
373        .get(range)
374        .ok_or_else(|| model_error("Footprint child span is outside source", Position::START))?;
375    crate::sexpr::parse(selected)?;
376    Ok(())
377}
378
379fn selected_form_span(range: Range<usize>, head: &str) -> FormSpan {
380    FormSpan {
381        head: Some(head.to_owned()),
382        path: vec![head.to_owned()],
383        depth: 0,
384        range,
385        start: Position::START,
386        end: Position::START,
387    }
388}
389
390fn parse_line(
391    source: &str,
392    span: &FormSpan,
393    max_operations: usize,
394) -> Result<Vec<PlotterOperation>, Error> {
395    let form = parse_span(source, span)?;
396    let start =
397        child(&form, "start").ok_or_else(|| model_error("fp_line requires start", span.start))?;
398    let end = child(&form, "end").ok_or_else(|| model_error("fp_line requires end", span.start))?;
399    let start_x = mm_to_nm(numeric_at(start, 1, span.start)?)?;
400    let start_y = mm_to_nm(numeric_at(start, 2, span.start)?)?;
401    let end_x = mm_to_nm(numeric_at(end, 1, span.start)?)?;
402    let end_y = mm_to_nm(numeric_at(end, 2, span.start)?)?;
403    let layer = child(&form, "layer")
404        .and_then(|value| value_at(value, 1))
405        .unwrap_or(DEFAULT_LINE_LAYER)
406        .to_owned();
407    let stroke = parse_stroke(&form, span.start)?;
408    let solid = ThickSegment {
409        start_x,
410        start_y,
411        end_x,
412        end_y,
413        width_nm: stroke.width_nm,
414        layer: Some(layer.clone()),
415        role: None,
416        layers: Vec::new(),
417        mask_margin_nm: None,
418        pad_size_x_nm: None,
419        pad_size_y_nm: None,
420    };
421    if matches!(stroke.style, StrokeStyle::Default | StrokeStyle::Solid) {
422        return Ok(vec![PlotterOperation::ThickSegment(solid)]);
423    }
424    let pieces = decompose_segment(
425        start_x,
426        start_y,
427        end_x,
428        end_y,
429        stroke.width_nm,
430        stroke.style,
431        max_operations,
432    )?;
433    if pieces.is_empty() {
434        return Ok(vec![PlotterOperation::ThickSegment(solid)]);
435    }
436    Ok(pieces
437        .into_iter()
438        .map(|[start_x, start_y, end_x, end_y]| {
439            PlotterOperation::ThickSegment(ThickSegment {
440                start_x,
441                start_y,
442                end_x,
443                end_y,
444                width_nm: stroke.width_nm,
445                layer: Some(layer.clone()),
446                role: None,
447                layers: Vec::new(),
448                mask_margin_nm: None,
449                pad_size_x_nm: None,
450                pad_size_y_nm: None,
451            })
452        })
453        .collect())
454}
455
456fn parse_arc(
457    source: &str,
458    span: &FormSpan,
459    max_operations: usize,
460) -> Result<Vec<PlotterOperation>, Error> {
461    let form = parse_span(source, span)?;
462    let start =
463        child(&form, "start").ok_or_else(|| model_error("fp_arc requires start", span.start))?;
464    let mid = child(&form, "mid").ok_or_else(|| model_error("fp_arc requires mid", span.start))?;
465    let end = child(&form, "end").ok_or_else(|| model_error("fp_arc requires end", span.start))?;
466    let start_x = mm_to_nm(numeric_at(start, 1, span.start)?)?;
467    let start_y = mm_to_nm(numeric_at(start, 2, span.start)?)?;
468    let mid_x = mm_to_nm(numeric_at(mid, 1, span.start)?)?;
469    let mid_y = mm_to_nm(numeric_at(mid, 2, span.start)?)?;
470    let end_x = mm_to_nm(numeric_at(end, 1, span.start)?)?;
471    let end_y = mm_to_nm(numeric_at(end, 2, span.start)?)?;
472    let layer = graphic_layer(&form);
473    let stroke = parse_stroke(&form, span.start)?;
474    if matches!(stroke.style, StrokeStyle::Default | StrokeStyle::Solid) {
475        return Ok(vec![PlotterOperation::ArcThreePoint(ArcThreePoint {
476            start_x,
477            start_y,
478            mid_x,
479            mid_y,
480            end_x,
481            end_y,
482            fill: PlotterFill::NoFill,
483            width_nm: stroke.width_nm,
484            layer: Some(layer),
485            stroke_color: None,
486            fill_color: None,
487            line_style: None,
488        })]);
489    }
490    let pieces = decompose_arc(
491        [start_x, start_y],
492        [mid_x, mid_y],
493        [end_x, end_y],
494        stroke.width_nm,
495        stroke.style,
496        max_operations,
497    )?;
498    if pieces.is_empty() {
499        return Ok(vec![PlotterOperation::ArcThreePoint(ArcThreePoint {
500            start_x,
501            start_y,
502            mid_x,
503            mid_y,
504            end_x,
505            end_y,
506            fill: PlotterFill::NoFill,
507            width_nm: stroke.width_nm,
508            layer: Some(layer),
509            stroke_color: None,
510            fill_color: None,
511            line_style: None,
512        })]);
513    }
514    Ok(pieces
515        .into_iter()
516        .map(|[start_x, start_y, end_x, end_y]| {
517            PlotterOperation::ThickSegment(ThickSegment {
518                start_x,
519                start_y,
520                end_x,
521                end_y,
522                width_nm: stroke.width_nm,
523                layer: Some(layer.clone()),
524                role: None,
525                layers: Vec::new(),
526                mask_margin_nm: None,
527                pad_size_x_nm: None,
528                pad_size_y_nm: None,
529            })
530        })
531        .collect())
532}
533
534fn parse_circle(source: &str, span: &FormSpan) -> Result<PlotterOperation, Error> {
535    let form = parse_span(source, span)?;
536    let center = child(&form, "center")
537        .ok_or_else(|| model_error("fp_circle requires center", span.start))?;
538    let end =
539        child(&form, "end").ok_or_else(|| model_error("fp_circle requires end", span.start))?;
540    let center_x_mm = numeric_at(center, 1, span.start)?;
541    let center_y_mm = numeric_at(center, 2, span.start)?;
542    let end_x_mm = numeric_at(end, 1, span.start)?;
543    let end_y_mm = numeric_at(end, 2, span.start)?;
544    let stroke = parse_stroke(&form, span.start)?;
545    Ok(PlotterOperation::Circle(PlotterCircle {
546        cx: mm_to_nm(center_x_mm)?,
547        cy: mm_to_nm(center_y_mm)?,
548        diameter_nm: mm_to_nm(2.0 * (end_x_mm - center_x_mm).hypot(end_y_mm - center_y_mm))?,
549        fill: graphic_fill(&form),
550        width_nm: stroke.width_nm,
551        layer: Some(graphic_layer(&form)),
552        role: None,
553        layers: Vec::new(),
554        mask_margin_nm: None,
555        pad_size_x_nm: None,
556        pad_size_y_nm: None,
557        stroke_color: None,
558        fill_color: None,
559        line_style: None,
560    }))
561}
562
563fn parse_rect(source: &str, span: &FormSpan) -> Result<PlotterOperation, Error> {
564    let form = parse_span(source, span)?;
565    let start =
566        child(&form, "start").ok_or_else(|| model_error("fp_rect requires start", span.start))?;
567    let end = child(&form, "end").ok_or_else(|| model_error("fp_rect requires end", span.start))?;
568    let stroke = parse_stroke(&form, span.start)?;
569    Ok(PlotterOperation::Rect(PlotterRect {
570        x1: mm_to_nm(numeric_at(start, 1, span.start)?)?,
571        y1: mm_to_nm(numeric_at(start, 2, span.start)?)?,
572        x2: mm_to_nm(numeric_at(end, 1, span.start)?)?,
573        y2: mm_to_nm(numeric_at(end, 2, span.start)?)?,
574        fill: graphic_fill(&form),
575        width_nm: stroke.width_nm,
576        corner_radius_nm: 0,
577        layer: Some(graphic_layer(&form)),
578        stroke_color: None,
579        fill_color: None,
580        line_style: None,
581    }))
582}
583
584fn parse_poly(source: &str, span: &FormSpan, max_points: usize) -> Result<PlotterOperation, Error> {
585    let form = parse_span(source, span)?;
586    let points_form =
587        child(&form, "pts").ok_or_else(|| model_error("fp_poly requires pts", span.start))?;
588    let point_forms = list(points_form)
589        .ok_or_else(|| model_error("fp_poly pts must be a list", span.start))?
590        .iter()
591        .skip(1)
592        .filter(|value| {
593            list(value)
594                .and_then(|items| items.first())
595                .and_then(sexp_text)
596                == Some("xy")
597        });
598    let mut points = Vec::new();
599    for value in point_forms {
600        if points.len() >= max_points {
601            return Err(geometry_limit_error());
602        }
603        points.push([
604            mm_to_nm(numeric_at(value, 1, span.start)?)?,
605            mm_to_nm(numeric_at(value, 2, span.start)?)?,
606        ]);
607    }
608    let stroke = parse_stroke(&form, span.start)?;
609    Ok(PlotterOperation::PlotPoly(PlotterPoly {
610        points,
611        fill: graphic_fill(&form),
612        width_nm: stroke.width_nm,
613        layer: Some(graphic_layer(&form)),
614        stroke_color: None,
615        fill_color: None,
616        line_style: None,
617    }))
618}
619
620#[derive(Clone, Copy, Debug, Default)]
621struct PadDrill {
622    oval: bool,
623    diameter_mm: Option<f64>,
624    width_mm: Option<f64>,
625    height_mm: Option<f64>,
626    offset_x_mm: f64,
627    offset_y_mm: f64,
628}
629
630impl PadDrill {
631    /// The hole for the NPTH copper rule; a round hole is its diameter on
632    /// both axes, an oblong one without a height is as tall as wide.
633    fn npth_hole(&self) -> Option<NpthHole> {
634        let size_mm = if self.oval {
635            let width = self.width_mm?;
636            [width, self.height_mm.unwrap_or(width)]
637        } else {
638            let diameter = self.diameter_mm?;
639            [diameter, diameter]
640        };
641        Some(NpthHole {
642            oblong: self.oval,
643            size_mm,
644            pad_offset_mm: [self.offset_x_mm, self.offset_y_mm],
645        })
646    }
647}
648
649#[derive(Clone, Copy, Debug)]
650struct PadOperationContext<'a> {
651    x: i64,
652    y: i64,
653    orient_deg: f64,
654    size_x_nm: i64,
655    size_y_nm: i64,
656    pad_type: &'a str,
657    layers: &'a [String],
658    mask_margin_nm: i64,
659}
660
661#[allow(
662    clippy::too_many_lines,
663    reason = "pre-standard pad dispatch retained under the structural ratchet"
664)]
665fn parse_pad(
666    source: &str,
667    span: &FormSpan,
668    footprint_mask_margin_mm: f64,
669    orient_deg_offset: f64,
670    max_operations: usize,
671    max_points: usize,
672) -> Result<FootprintPadOperations, Error> {
673    let form = parse_span(source, span)?;
674    let values = list(&form).ok_or_else(|| model_error("pad must be a list", span.start))?;
675    let pad_type = values.get(2).and_then(sexp_text).unwrap_or("");
676    let shape = values.get(3).and_then(sexp_text).unwrap_or("");
677    let at = child(&form, "at");
678    let x = mm_to_nm(optional_numeric_at(at, 1, 0.0, span.start)?)?;
679    let y = mm_to_nm(optional_numeric_at(at, 2, 0.0, span.start)?)?;
680    let orient_deg = finite_number(
681        optional_numeric_at(at, 3, 0.0, span.start)? + orient_deg_offset,
682        span.start,
683    )?;
684    let size = child(&form, "size");
685    let size_x_mm = optional_numeric_at(size, 1, 0.0, span.start)?;
686    let size_y_mm = optional_numeric_at(size, 2, 0.0, span.start)?;
687    let size_x_nm = mm_to_nm(size_x_mm)?;
688    let size_y_nm = mm_to_nm(size_y_mm)?;
689    let layers = child(&form, "layers")
690        .and_then(list)
691        .map(|values| {
692            values
693                .iter()
694                .skip(1)
695                .filter_map(sexp_text)
696                .map(str::to_owned)
697                .collect::<Vec<_>>()
698        })
699        .unwrap_or_default();
700    let requested_mask_margin = child(&form, "solder_mask_margin")
701        .map(|value| numeric_at(value, 1, span.start))
702        .transpose()?
703        .unwrap_or(footprint_mask_margin_mm);
704    let mask_margin_nm = mm_to_nm(requested_mask_margin.max(-size_x_mm.min(size_y_mm) / 2.0))?;
705    let drill = parse_pad_drill(&form, span.start)?;
706    let suppress_npth_flash =
707        npth_flash_is_suppressed(pad_type, shape, [size_x_mm, size_y_mm], drill.npth_hole());
708    let base_context = PadOperationContext {
709        x,
710        y,
711        orient_deg,
712        size_x_nm,
713        size_y_nm,
714        pad_type,
715        layers: &layers,
716        mask_margin_nm,
717    };
718    let offset_x_nm = mm_to_nm(drill.offset_x_mm)?;
719    let offset_y_nm = mm_to_nm(drill.offset_y_mm)?;
720    let [offset_x_nm, offset_y_nm] = rotate_nm(offset_x_nm, offset_y_nm, orient_deg)?;
721    let context = PadOperationContext {
722        x: checked_safe_add(x, offset_x_nm)?,
723        y: checked_safe_add(y, offset_y_nm)?,
724        ..base_context
725    };
726
727    let mut output = FootprintPadOperations::default();
728    if !suppress_npth_flash {
729        let flash = match shape {
730            "circle" => Some(PlotterOperation::FlashPadCircle(FlashPadCircle {
731                x: context.x,
732                y: context.y,
733                diameter_nm: size_x_nm,
734                layers: layers.clone(),
735                mask_margin_nm,
736            })),
737            "oval" => Some(PlotterOperation::FlashPadOval(FlashPadOval {
738                x: context.x,
739                y: context.y,
740                size_x_nm,
741                size_y_nm,
742                orient_deg,
743                layers: layers.clone(),
744                mask_margin_nm,
745            })),
746            "rect" => Some(PlotterOperation::FlashPadRect(FlashPadRect {
747                x: context.x,
748                y: context.y,
749                size_x_nm,
750                size_y_nm,
751                orient_deg,
752                layers: layers.clone(),
753                mask_margin_nm,
754            })),
755            "roundrect" => Some(parse_roundrect_flash(
756                &form, span.start, context, max_points,
757            )?),
758            "custom" => Some(parse_custom_pad_flash(
759                &form, span.start, context, max_points,
760            )?),
761            "trapezoid" => {
762                let delta = child(&form, "rect_delta");
763                let delta_x = mm_to_nm(optional_numeric_at(delta, 1, 0.0, span.start)?)? / 2;
764                let delta_y = mm_to_nm(optional_numeric_at(delta, 2, 0.0, span.start)?)? / 2;
765                let half_x = size_x_nm / 2;
766                let half_y = size_y_nm / 2;
767                Some(PlotterOperation::FlashPadTrapez(FlashPadTrapez {
768                    x: context.x,
769                    y: context.y,
770                    size_x_nm,
771                    size_y_nm,
772                    corners: [
773                        [
774                            checked_safe_add(-half_x, -delta_y)?,
775                            checked_safe_add(half_y, delta_x)?,
776                        ],
777                        [
778                            checked_safe_add(half_x, delta_y)?,
779                            checked_safe_add(half_y, -delta_x)?,
780                        ],
781                        [
782                            checked_safe_add(half_x, -delta_y)?,
783                            checked_safe_add(-half_y, delta_x)?,
784                        ],
785                        [
786                            checked_safe_add(-half_x, delta_y)?,
787                            checked_safe_add(-half_y, -delta_x)?,
788                        ],
789                    ],
790                    orient_deg,
791                    layers: layers.clone(),
792                    mask_margin_nm,
793                }))
794            }
795            _ => None,
796        };
797        if let Some(flash) = flash {
798            push_plotter_operation(&mut output.flash, flash, max_operations)?;
799        }
800    }
801
802    if matches!(pad_type, "thru_hole" | "np_thru_hole")
803        && let Some(drill_operation) = pad_drill_operation(base_context, drill)?
804    {
805        if output.flash.len() >= max_operations {
806            return Err(limit_error());
807        }
808        push_plotter_operation(
809            &mut output.drill,
810            drill_operation,
811            max_operations - output.flash.len(),
812        )?;
813    }
814    Ok(output)
815}
816
817/// An NPTH pad's hole as pcbnew's copper rule reads it, in millimetres.
818#[derive(Clone, Copy, Debug)]
819pub(crate) struct NpthHole {
820    pub oblong: bool,
821    pub size_mm: [f64; 2],
822    /// The pad shape's offset from the hole (`(drill (offset x y))`).
823    pub pad_offset_mm: [f64; 2],
824}
825
826/// Half a KiCad internal unit (1 nm), in millimetres: the file's decimals
827/// compare as pcbnew's integers do.
828const HALF_IU_MM: f64 = 0.5e-6;
829
830/// pcbnew plots no copper for an NPTH pad its hole covers: a circle on a
831/// round hole at least as wide, or an oval on an oblong hole at least as
832/// large on both axes, the pad centred on the hole (`PAD::FlashLayer`); or a
833/// circle or oval exactly the hole's size (the Gerber plot's NPTH skip in
834/// `PlotStandardLayer`, whatever the hole's shape).
835pub(crate) fn npth_flash_is_suppressed(
836    pad_type: &str,
837    shape: &str,
838    size_mm: [f64; 2],
839    hole: Option<NpthHole>,
840) -> bool {
841    let Some(hole) = hole.filter(|_| pad_type == "np_thru_hole") else {
842        return false;
843    };
844    let covers = |axis: usize| hole.size_mm[axis] >= size_mm[axis] - HALF_IU_MM;
845    let equal = |axis: usize| (hole.size_mm[axis] - size_mm[axis]).abs() < HALF_IU_MM;
846    let centred = hole
847        .pad_offset_mm
848        .iter()
849        .all(|value| value.abs() < HALF_IU_MM);
850    let flash_off = centred
851        && match (shape, hole.oblong) {
852            ("circle", false) => covers(0),
853            ("oval", true) => covers(0) && covers(1),
854            _ => false,
855        };
856    let plot_skip = matches!(shape, "circle" | "oval") && equal(0) && equal(1);
857    flash_off || plot_skip
858}
859
860fn parse_roundrect_flash(
861    form: &Sexp,
862    position: Position,
863    context: PadOperationContext<'_>,
864    max_points: usize,
865) -> Result<PlotterOperation, Error> {
866    let round_ratio = child(form, "roundrect_rratio")
867        .map(|value| numeric_at(value, 1, position))
868        .transpose()?
869        .unwrap_or(0.25);
870    let corner_radius_nm =
871        rounded_safe_f64(context.size_x_nm.min(context.size_y_nm) as f64 * round_ratio)?;
872    let chamfer_ratio = child(form, "chamfer_ratio")
873        .map(|value| numeric_at(value, 1, position))
874        .transpose()?
875        .unwrap_or(0.0);
876    let chamfer_corners = child(form, "chamfer")
877        .and_then(list)
878        .map(|values| {
879            values
880                .iter()
881                .skip(1)
882                .filter_map(sexp_text)
883                .collect::<Vec<_>>()
884        })
885        .unwrap_or_default();
886    if !chamfer_corners.is_empty() && chamfer_ratio > 0.0 && corner_radius_nm < 1 {
887        let polygon = chamfered_pad_polygon(
888            context.size_x_nm,
889            context.size_y_nm,
890            chamfer_ratio,
891            &chamfer_corners,
892        )?;
893        if polygon.len() > max_points {
894            return Err(geometry_limit_error());
895        }
896        return Ok(PlotterOperation::FlashPadCustom(FlashPadCustom {
897            x: context.x,
898            y: context.y,
899            size_x_nm: context.size_x_nm,
900            size_y_nm: context.size_y_nm,
901            orient_deg: context.orient_deg,
902            polygons: vec![polygon],
903            polygon_widths_nm: None,
904            anchor_shape: None,
905            layers: context.layers.to_vec(),
906            mask_margin_nm: context.mask_margin_nm,
907        }));
908    }
909    Ok(PlotterOperation::FlashPadRoundRect(FlashPadRoundRect {
910        x: context.x,
911        y: context.y,
912        size_x_nm: context.size_x_nm,
913        size_y_nm: context.size_y_nm,
914        corner_radius_nm,
915        orient_deg: context.orient_deg,
916        layers: context.layers.to_vec(),
917        mask_margin_nm: context.mask_margin_nm,
918    }))
919}
920
921fn parse_custom_pad_flash(
922    form: &Sexp,
923    position: Position,
924    context: PadOperationContext<'_>,
925    max_points: usize,
926) -> Result<PlotterOperation, Error> {
927    let mut polygons = Vec::new();
928    let mut polygon_widths_nm = Vec::new();
929    let mut point_count = 0usize;
930    if let Some(primitives) = child(form, "primitives").and_then(list) {
931        for primitive in primitives.iter().skip(1) {
932            if value_at(primitive, 0) != Some("gr_poly") {
933                continue;
934            }
935            let Some(points) = child(primitive, "pts").and_then(list) else {
936                continue;
937            };
938            let mut polygon = Vec::new();
939            for point in points
940                .iter()
941                .skip(1)
942                .filter(|point| value_at(point, 0) == Some("xy"))
943            {
944                if point_count >= max_points {
945                    return Err(geometry_limit_error());
946                }
947                polygon.push([
948                    mm_to_nm(numeric_at(point, 1, position)?)?,
949                    mm_to_nm(numeric_at(point, 2, position)?)?,
950                ]);
951                point_count = point_count.saturating_add(1);
952            }
953            if polygon.is_empty() {
954                continue;
955            }
956            polygons.push(polygon);
957            let width_mm = child(primitive, "width")
958                .map(|width| numeric_at(width, 1, position))
959                .transpose()?
960                .unwrap_or(0.0);
961            polygon_widths_nm.push(mm_to_nm(width_mm)?);
962        }
963    }
964    let anchor_shape = child(form, "options")
965        .and_then(|options| child(options, "anchor"))
966        .and_then(|anchor| value_at(anchor, 1))
967        .filter(|anchor| !anchor.is_empty())
968        .map(str::to_owned);
969    Ok(PlotterOperation::FlashPadCustom(FlashPadCustom {
970        x: context.x,
971        y: context.y,
972        size_x_nm: context.size_x_nm,
973        size_y_nm: context.size_y_nm,
974        orient_deg: context.orient_deg,
975        polygons,
976        polygon_widths_nm: Some(polygon_widths_nm),
977        anchor_shape,
978        layers: context.layers.to_vec(),
979        mask_margin_nm: context.mask_margin_nm,
980    }))
981}
982
983fn chamfered_pad_polygon(
984    size_x_nm: i64,
985    size_y_nm: i64,
986    chamfer_ratio: f64,
987    chamfer_corners: &[&str],
988) -> Result<Vec<[i64; 2]>, Error> {
989    let half_width = size_x_nm as f64 / 2.0;
990    let half_height = size_y_nm as f64 / 2.0;
991    let shorter = size_x_nm.min(size_y_nm) as f64;
992    let chamfer = (chamfer_ratio * shorter).max(0.0);
993    let mut corners = vec![
994        [-half_width, -half_height],
995        [half_width, -half_height],
996        [half_width, half_height],
997        [-half_width, half_height],
998    ];
999    if chamfer > 0.0 {
1000        let corner_names = ["top_left", "top_right", "bottom_right", "bottom_left"];
1001        let sign = [0.0, 1.0, -1.0, 0.0, 0.0, -1.0, 1.0, 0.0];
1002        let chamfer_count = corner_names
1003            .iter()
1004            .filter(|name| chamfer_corners.contains(name))
1005            .count();
1006        let mut position = 0;
1007        for (corner_index, name) in corner_names.iter().enumerate() {
1008            if !chamfer_corners.contains(name) {
1009                position += 1;
1010                continue;
1011            }
1012            corners.insert(position + 1, corners[position]);
1013            corners[position][0] += sign[(2 * corner_index) & 7] * chamfer;
1014            corners[position][1] += sign[(2 * corner_index + 6) & 7] * chamfer;
1015            corners[position + 1][0] += sign[(2 * corner_index + 1) & 7] * chamfer;
1016            corners[position + 1][1] += sign[(2 * corner_index + 7) & 7] * chamfer;
1017            position += 2;
1018        }
1019        if chamfer_count > 1 && 2.0 * chamfer >= shorter {
1020            corners.dedup_by(|right, left| {
1021                (right[0] - left[0]).abs() <= 1e-9 && (right[1] - left[1]).abs() <= 1e-9
1022            });
1023            if corners.len() > 1 {
1024                let first = corners[0];
1025                let last = corners[corners.len() - 1];
1026                if (first[0] - last[0]).abs() < 1e-9 && (first[1] - last[1]).abs() < 1e-9 {
1027                    corners.pop();
1028                }
1029            }
1030        }
1031    }
1032    corners
1033        .into_iter()
1034        .map(|[x, y]| Ok([rounded_safe_f64(x)?, rounded_safe_f64(y)?]))
1035        .collect()
1036}
1037
1038fn parse_pad_drill(form: &Sexp, position: Position) -> Result<PadDrill, Error> {
1039    let Some(drill) = child(form, "drill") else {
1040        return Ok(PadDrill::default());
1041    };
1042    let offset = child(drill, "offset");
1043    let offset_x_mm = optional_numeric_at(offset, 1, 0.0, position)?;
1044    let offset_y_mm = optional_numeric_at(offset, 2, 0.0, position)?;
1045    if value_at(drill, 1) == Some("oval") {
1046        let width_mm = drill_size(drill, 2, position)?;
1047        let height_mm = drill_size(drill, 3, position)?;
1048        return Ok(PadDrill {
1049            oval: true,
1050            diameter_mm: width_mm,
1051            width_mm,
1052            height_mm,
1053            offset_x_mm,
1054            offset_y_mm,
1055        });
1056    }
1057    Ok(PadDrill {
1058        diameter_mm: drill_size(drill, 1, position)?,
1059        offset_x_mm,
1060        offset_y_mm,
1061        ..PadDrill::default()
1062    })
1063}
1064
1065/// The drill size at `index`, or none when the drill states only its
1066/// offset: `(drill (offset x y))` gives an SMD pad's shape offset, no hole.
1067fn drill_size(drill: &Sexp, index: usize, position: Position) -> Result<Option<f64>, Error> {
1068    match list(drill).and_then(|values| values.get(index)) {
1069        None | Some(Sexp::List(_)) => Ok(None),
1070        Some(value) => numeric_value(value, position).map(Some),
1071    }
1072}
1073
1074fn pad_drill_operation(
1075    context: PadOperationContext<'_>,
1076    drill: PadDrill,
1077) -> Result<Option<PlotterOperation>, Error> {
1078    let role = if context.pad_type == "np_thru_hole" {
1079        "npth_hole"
1080    } else {
1081        "pad_drill"
1082    };
1083    let center = [context.x, context.y];
1084
1085    if drill.oval
1086        && let (Some(width_mm), Some(height_mm)) = (drill.width_mm, drill.height_mm)
1087        && width_mm > 0.0
1088        && height_mm > 0.0
1089    {
1090        return drill_slot_operation(
1091            context,
1092            center,
1093            mm_to_nm(width_mm)?,
1094            mm_to_nm(height_mm)?,
1095            role,
1096        );
1097    }
1098    if let Some(diameter_mm) = drill.diameter_mm.filter(|value| *value > 0.0) {
1099        return Ok(Some(drill_circle_operation(
1100            context,
1101            center,
1102            mm_to_nm(diameter_mm)?,
1103            role,
1104        )));
1105    }
1106    if context.pad_type == "np_thru_hole" {
1107        let fallback = context.size_x_nm.min(context.size_y_nm);
1108        if fallback > 0 {
1109            return Ok(Some(drill_circle_operation(
1110                context, center, fallback, role,
1111            )));
1112        }
1113    }
1114    Ok(None)
1115}
1116
1117fn drill_circle_operation(
1118    context: PadOperationContext<'_>,
1119    [cx, cy]: [i64; 2],
1120    diameter_nm: i64,
1121    role: &str,
1122) -> PlotterOperation {
1123    let npth = role == "npth_hole";
1124    PlotterOperation::Circle(PlotterCircle {
1125        cx,
1126        cy,
1127        diameter_nm,
1128        fill: PlotterFill::FilledShape,
1129        width_nm: 0,
1130        layer: None,
1131        role: Some(role.to_owned()),
1132        layers: context.layers.to_vec(),
1133        mask_margin_nm: npth.then_some(context.mask_margin_nm),
1134        pad_size_x_nm: npth.then_some(context.size_x_nm),
1135        pad_size_y_nm: npth.then_some(context.size_y_nm),
1136        stroke_color: None,
1137        fill_color: None,
1138        line_style: None,
1139    })
1140}
1141
1142fn drill_slot_operation(
1143    context: PadOperationContext<'_>,
1144    [cx, cy]: [i64; 2],
1145    width_nm: i64,
1146    height_nm: i64,
1147    role: &str,
1148) -> Result<Option<PlotterOperation>, Error> {
1149    let major = width_nm.max(height_nm);
1150    let minor = width_nm.min(height_nm);
1151    if major <= 0 || minor <= 0 {
1152        return Ok(None);
1153    }
1154    let mut theta = (-context.orient_deg).to_radians();
1155    if height_nm > width_nm {
1156        theta += std::f64::consts::FRAC_PI_2;
1157    }
1158    let half_length = (major - minor) as f64 / 2.0;
1159    let dx = rounded_safe_f64(theta.cos() * half_length)?;
1160    let dy = rounded_safe_f64(theta.sin() * half_length)?;
1161    if dx == 0 && dy == 0 {
1162        return Ok(Some(drill_circle_operation(context, [cx, cy], minor, role)));
1163    }
1164    Ok(Some(PlotterOperation::ThickSegment(ThickSegment {
1165        start_x: checked_safe_add(cx, -dx)?,
1166        start_y: checked_safe_add(cy, -dy)?,
1167        end_x: checked_safe_add(cx, dx)?,
1168        end_y: checked_safe_add(cy, dy)?,
1169        width_nm: minor,
1170        layer: None,
1171        role: Some(role.to_owned()),
1172        layers: context.layers.to_vec(),
1173        mask_margin_nm: (role == "npth_hole").then_some(context.mask_margin_nm),
1174        pad_size_x_nm: (role == "npth_hole").then_some(context.size_x_nm),
1175        pad_size_y_nm: (role == "npth_hole").then_some(context.size_y_nm),
1176    })))
1177}
1178
1179fn rotate_nm(x: i64, y: i64, orient_deg: f64) -> Result<[i64; 2], Error> {
1180    if orient_deg == 0.0 {
1181        return Ok([x, y]);
1182    }
1183    let theta = (-orient_deg).to_radians();
1184    Ok([
1185        rounded_safe_f64(x as f64 * theta.cos() - y as f64 * theta.sin())?,
1186        rounded_safe_f64(x as f64 * theta.sin() + y as f64 * theta.cos())?,
1187    ])
1188}
1189
1190fn checked_safe_add(left: i64, right: i64) -> Result<i64, Error> {
1191    left.checked_add(right)
1192        .and_then(|value| ensure_javascript_safe_integer(value).ok())
1193        .ok_or_else(|| {
1194            model_error(
1195                "Pad coordinate exceeds JavaScript safe-integer range",
1196                Position::START,
1197            )
1198        })
1199}
1200
1201fn push_plotter_operation(
1202    output: &mut Vec<PlotterOperation>,
1203    operation: PlotterOperation,
1204    max_operations: usize,
1205) -> Result<(), Error> {
1206    if output.len() >= max_operations {
1207        return Err(limit_error());
1208    }
1209    output.push(operation);
1210    Ok(())
1211}
1212
1213fn append_operations(
1214    operations: &mut Vec<PlotterOperation>,
1215    additions: Vec<PlotterOperation>,
1216    max_operations: usize,
1217) -> Result<(), Error> {
1218    if additions.len() > max_operations.saturating_sub(operations.len()) {
1219        return Err(limit_error());
1220    }
1221    operations.extend(additions);
1222    Ok(())
1223}
1224
1225fn append_bounded_operations(
1226    operations: &mut Vec<PlotterOperation>,
1227    additions: Vec<PlotterOperation>,
1228    limits: FootprintPlotLimits,
1229    point_count: &mut usize,
1230) -> Result<(), Error> {
1231    let added_points = additions
1232        .iter()
1233        .map(operation_point_count)
1234        .try_fold(0usize, usize::checked_add)
1235        .ok_or_else(geometry_limit_error)?;
1236    if added_points > limits.max_points.saturating_sub(*point_count) {
1237        return Err(geometry_limit_error());
1238    }
1239    append_operations(operations, additions, limits.max_operations)?;
1240    *point_count = point_count.saturating_add(added_points);
1241    Ok(())
1242}
1243
1244fn operation_point_count(operation: &PlotterOperation) -> usize {
1245    match operation {
1246        PlotterOperation::PlotPoly(value) => value.points.len(),
1247        PlotterOperation::FlashPadCustom(value) => {
1248            value.polygons.iter().map(Vec::len).sum::<usize>()
1249        }
1250        _ => 0,
1251    }
1252}
1253
1254fn remaining_operations(
1255    operations: &[PlotterOperation],
1256    limits: FootprintPlotLimits,
1257) -> Result<usize, Error> {
1258    limits
1259        .max_operations
1260        .checked_sub(operations.len())
1261        .filter(|remaining| *remaining > 0)
1262        .ok_or_else(limit_error)
1263}
1264
1265#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1266pub(crate) enum StrokeStyle {
1267    Default,
1268    Solid,
1269    Dash,
1270    Dot,
1271    DashDot,
1272    DashDotDot,
1273}
1274
1275#[derive(Clone, Copy, Debug)]
1276struct StrokeSpec {
1277    width_nm: i64,
1278    style: StrokeStyle,
1279}
1280
1281fn parse_stroke(form: &Sexp, position: Position) -> Result<StrokeSpec, Error> {
1282    let stroke = child(form, "stroke");
1283    let width_mm = stroke
1284        .and_then(|value| child(value, "width"))
1285        .map(|value| numeric_at(value, 1, position))
1286        .transpose()?
1287        .unwrap_or(0.0);
1288    let width_nm = if width_mm < 0.0 {
1289        0
1290    } else if width_mm == 0.0 {
1291        DEFAULT_STROKE_WIDTH_NM.max(MIN_PLOT_PEN_WIDTH_NM)
1292    } else {
1293        mm_to_nm(width_mm)?.max(MIN_PLOT_PEN_WIDTH_NM)
1294    };
1295    let style = match stroke
1296        .and_then(|value| child(value, "type"))
1297        .and_then(|value| value_at(value, 1))
1298        .unwrap_or("default")
1299    {
1300        "default" => StrokeStyle::Default,
1301        "solid" => StrokeStyle::Solid,
1302        "dash" => StrokeStyle::Dash,
1303        "dot" => StrokeStyle::Dot,
1304        "dash_dot" => StrokeStyle::DashDot,
1305        "dash_dot_dot" => StrokeStyle::DashDotDot,
1306        _ => return Err(model_error("Unsupported footprint stroke type", position)),
1307    };
1308    Ok(StrokeSpec { width_nm, style })
1309}
1310
1311fn graphic_layer(form: &Sexp) -> String {
1312    child(form, "layer")
1313        .and_then(|value| value_at(value, 1))
1314        .unwrap_or(DEFAULT_LINE_LAYER)
1315        .to_owned()
1316}
1317
1318fn graphic_fill(form: &Sexp) -> PlotterFill {
1319    match child(form, "fill").and_then(|value| value_at(value, 1)) {
1320        Some("yes" | "solid") => PlotterFill::FilledShape,
1321        _ => PlotterFill::NoFill,
1322    }
1323}
1324
1325fn stroke_pattern(style: StrokeStyle, width_nm: i64) -> Result<(Vec<f64>, usize), Error> {
1326    if width_nm <= 0 {
1327        return Err(decomposition_limit_error(
1328            "Patterned stroke width cannot make forward progress",
1329        ));
1330    }
1331    let width = width_nm as f64;
1332    let dash = DASH_RATIO * width;
1333    let gap = GAP_RATIO * width;
1334    let dot = DOT_RATIO * width;
1335    match style {
1336        StrokeStyle::Dash => Ok((vec![dash, gap], 2)),
1337        StrokeStyle::Dot => Ok((vec![dot, gap], 2)),
1338        StrokeStyle::DashDot => Ok((vec![dash, gap, dot, gap], 4)),
1339        StrokeStyle::DashDotDot => Ok((vec![dash, gap, dot, gap, dot, gap], 6)),
1340        StrokeStyle::Default | StrokeStyle::Solid => Err(model_error(
1341            "Solid strokes do not require decomposition",
1342            Position::START,
1343        )),
1344    }
1345}
1346
1347pub(crate) fn decompose_segment(
1348    start_x: i64,
1349    start_y: i64,
1350    end_x: i64,
1351    end_y: i64,
1352    width_nm: i64,
1353    style: StrokeStyle,
1354    max_operations: usize,
1355) -> Result<Vec<[i64; 4]>, Error> {
1356    let (strokes, wrap) = stroke_pattern(style, width_nm)?;
1357    let delta_x = (end_x - start_x) as f64;
1358    let delta_y = (end_y - start_y) as f64;
1359    let total = delta_x.hypot(delta_y);
1360    if total <= 0.0 {
1361        return Ok(Vec::new());
1362    }
1363    let unit_x = delta_x / total;
1364    let unit_y = delta_y / total;
1365    let mut output = Vec::new();
1366    let mut current = 0.0;
1367    let mut index = 0usize;
1368    while current < total && index < MAX_DECOMPOSITION_STEPS {
1369        let next = current + strokes[index % wrap];
1370        if !next.is_finite() || next <= current {
1371            return Err(decomposition_limit_error(
1372                "Patterned segment decomposition cannot make forward progress",
1373            ));
1374        }
1375        if index.is_multiple_of(2) {
1376            let end_along = next.min(total);
1377            if end_along > current {
1378                push_decomposed_segment(
1379                    &mut output,
1380                    [
1381                        rounded_safe_f64(start_x as f64 + unit_x * current)?,
1382                        rounded_safe_f64(start_y as f64 + unit_y * current)?,
1383                        rounded_safe_f64(start_x as f64 + unit_x * end_along)?,
1384                        rounded_safe_f64(start_y as f64 + unit_y * end_along)?,
1385                    ],
1386                    max_operations,
1387                )?;
1388            }
1389        }
1390        current = next;
1391        index += 1;
1392    }
1393    if current < total {
1394        return Err(decomposition_limit_error(
1395            "Patterned segment decomposition exceeds the safety step limit",
1396        ));
1397    }
1398    Ok(output)
1399}
1400
1401pub(crate) fn decompose_arc(
1402    start: [i64; 2],
1403    mid: [i64; 2],
1404    end: [i64; 2],
1405    width_nm: i64,
1406    style: StrokeStyle,
1407    max_operations: usize,
1408) -> Result<Vec<[i64; 4]>, Error> {
1409    let (strokes, wrap) = stroke_pattern(style, width_nm)?;
1410    let Some((center_x, center_y, radius)) = arc_center_radius(start, mid, end) else {
1411        return decompose_segment(
1412            start[0],
1413            start[1],
1414            end[0],
1415            end[1],
1416            width_nm,
1417            style,
1418            max_operations,
1419        );
1420    };
1421    if radius <= 0.0 {
1422        return Ok(Vec::new());
1423    }
1424    let circumference = std::f64::consts::TAU * radius;
1425    let start_angle_raw = (start[1] as f64 - center_y).atan2(start[0] as f64 - center_x);
1426    let mid_angle_raw = (mid[1] as f64 - center_y).atan2(mid[0] as f64 - center_x);
1427    let end_angle_raw = (end[1] as f64 - center_y).atan2(end[0] as f64 - center_x);
1428    let (start_angle, arc_end_angle) =
1429        normalize_arc_sweep(start_angle_raw, mid_angle_raw, end_angle_raw);
1430    let mut output = Vec::new();
1431    let mut index = 0usize;
1432    let mut current_angle = start_angle;
1433    while current_angle < arc_end_angle && index < MAX_DECOMPOSITION_STEPS {
1434        let segment_length = strokes[index % wrap];
1435        let theta = std::f64::consts::TAU * segment_length / circumference;
1436        if !theta.is_finite() || theta <= 0.0 {
1437            return Err(decomposition_limit_error(
1438                "Patterned arc decomposition cannot make forward progress",
1439            ));
1440        }
1441        let next_angle = (current_angle + theta).min(arc_end_angle);
1442        if !next_angle.is_finite() || next_angle <= current_angle {
1443            return Err(decomposition_limit_error(
1444                "Patterned arc decomposition cannot make forward progress",
1445            ));
1446        }
1447        if index.is_multiple_of(2) {
1448            let subdivide = style == StrokeStyle::Dash
1449                || (matches!(style, StrokeStyle::DashDot | StrokeStyle::DashDotDot)
1450                    && index.is_multiple_of(wrap));
1451            if subdivide {
1452                let mut low = current_angle;
1453                while low < next_angle {
1454                    let high = (low + ARC_CHORD_STEP_RADIANS).min(next_angle);
1455                    if !high.is_finite() || high <= low {
1456                        return Err(decomposition_limit_error(
1457                            "Patterned arc chord decomposition cannot make forward progress",
1458                        ));
1459                    }
1460                    push_arc_chord(
1461                        &mut output,
1462                        center_x,
1463                        center_y,
1464                        radius,
1465                        low,
1466                        high,
1467                        max_operations,
1468                    )?;
1469                    low = high;
1470                }
1471            } else {
1472                push_arc_chord(
1473                    &mut output,
1474                    center_x,
1475                    center_y,
1476                    radius,
1477                    current_angle,
1478                    next_angle,
1479                    max_operations,
1480                )?;
1481            }
1482        }
1483        current_angle = next_angle;
1484        index += 1;
1485    }
1486    if current_angle < arc_end_angle {
1487        return Err(decomposition_limit_error(
1488            "Patterned arc decomposition exceeds the safety step limit",
1489        ));
1490    }
1491    Ok(output)
1492}
1493
1494fn arc_center_radius(start: [i64; 2], mid: [i64; 2], end: [i64; 2]) -> Option<(f64, f64, f64)> {
1495    let start_x = start[0] as f64;
1496    let start_y = start[1] as f64;
1497    let mid_x = mid[0] as f64;
1498    let mid_y = mid[1] as f64;
1499    let end_x = end[0] as f64;
1500    let end_y = end[1] as f64;
1501    let a_x = mid_x - start_x;
1502    let a_y = mid_y - start_y;
1503    let b_x = end_x - mid_x;
1504    let b_y = end_y - mid_y;
1505    let denominator = 2.0 * (a_x * b_y - a_y * b_x);
1506    if denominator.abs() < 1e-9 {
1507        return None;
1508    }
1509    let start_squared = start_x * start_x + start_y * start_y;
1510    let mid_squared = mid_x * mid_x + mid_y * mid_y;
1511    let end_squared = end_x * end_x + end_y * end_y;
1512    let center_x = (start_squared * (mid_y - end_y)
1513        + mid_squared * (end_y - start_y)
1514        + end_squared * (start_y - mid_y))
1515        / denominator;
1516    let center_y = (start_squared * (end_x - mid_x)
1517        + mid_squared * (start_x - end_x)
1518        + end_squared * (mid_x - start_x))
1519        / denominator;
1520    Some((
1521        center_x,
1522        center_y,
1523        (start_x - center_x).hypot(start_y - center_y),
1524    ))
1525}
1526
1527fn normalize_arc_sweep(start: f64, mid: f64, end: f64) -> (f64, f64) {
1528    let tau = std::f64::consts::TAU;
1529    let start = start.rem_euclid(tau);
1530    let mid = mid.rem_euclid(tau);
1531    let end = end.rem_euclid(tau);
1532    let counter_clockwise_end = (end - start).rem_euclid(tau);
1533    let counter_clockwise_mid = (mid - start).rem_euclid(tau);
1534    if counter_clockwise_end == 0.0 {
1535        return (start, start + tau);
1536    }
1537    if counter_clockwise_mid > 0.0 && counter_clockwise_mid < counter_clockwise_end {
1538        return (start, start + counter_clockwise_end);
1539    }
1540    (end, end + (tau - counter_clockwise_end))
1541}
1542
1543fn push_arc_chord(
1544    output: &mut Vec<[i64; 4]>,
1545    center_x: f64,
1546    center_y: f64,
1547    radius: f64,
1548    low: f64,
1549    high: f64,
1550    max_operations: usize,
1551) -> Result<(), Error> {
1552    push_decomposed_segment(
1553        output,
1554        [
1555            rounded_safe_f64(center_x + radius * low.cos())?,
1556            rounded_safe_f64(center_y + radius * low.sin())?,
1557            rounded_safe_f64(center_x + radius * high.cos())?,
1558            rounded_safe_f64(center_y + radius * high.sin())?,
1559        ],
1560        max_operations,
1561    )
1562}
1563
1564fn push_decomposed_segment(
1565    output: &mut Vec<[i64; 4]>,
1566    segment: [i64; 4],
1567    max_operations: usize,
1568) -> Result<(), Error> {
1569    if output.len() >= max_operations {
1570        return Err(limit_error());
1571    }
1572    output.push(segment);
1573    Ok(())
1574}
1575
1576fn rounded_safe_f64(value: f64) -> Result<i64, Error> {
1577    if !value.is_finite()
1578        || value < JAVASCRIPT_SAFE_INTEGER_MIN as f64
1579        || value > JAVASCRIPT_SAFE_INTEGER_MAX as f64
1580    {
1581        return Err(model_error(
1582            "Graphic coordinate exceeds JavaScript safe-integer range",
1583            Position::START,
1584        ));
1585    }
1586    Ok(value.round_ties_even() as i64)
1587}
1588
1589fn form_integer(source: &str, span: &FormSpan, head: &str) -> Result<i64, Error> {
1590    let form = parse_span(source, span)?;
1591    match metadata_values(&form, head, span.start)?.first() {
1592        Some(Sexp::Integer(value)) => Ok(*value),
1593        Some(Sexp::Atom(value)) => value
1594            .parse::<i64>()
1595            .map_err(|_| model_error("Expected integer metadata", span.start)),
1596        _ => Err(model_error("Expected integer metadata", span.start)),
1597    }
1598}
1599
1600fn form_number(source: &str, span: &FormSpan, head: &str) -> Result<f64, Error> {
1601    let form = parse_span(source, span)?;
1602    let values = metadata_values(&form, head, span.start)?;
1603    let value = values
1604        .first()
1605        .ok_or_else(|| model_error("Metadata value is missing", span.start))?;
1606    finite_number(numeric_value(value, span.start)?, span.start)
1607}
1608
1609fn form_string(source: &str, span: &FormSpan, head: &str) -> Result<String, Error> {
1610    let form = parse_span(source, span)?;
1611    metadata_values(&form, head, span.start)?
1612        .first()
1613        .and_then(sexp_text)
1614        .map(str::to_owned)
1615        .ok_or_else(|| model_error("Metadata value is missing", span.start))
1616}
1617
1618fn form_strings(source: &str, span: &FormSpan, head: &str) -> Result<Vec<String>, Error> {
1619    let form = parse_span(source, span)?;
1620    let list = list(&form).ok_or_else(|| model_error("Expected list metadata", span.start))?;
1621    if list.first().and_then(sexp_text) != Some(head) {
1622        return Err(model_error("Unexpected metadata form", span.start));
1623    }
1624    Ok(list
1625        .iter()
1626        .skip(1)
1627        .filter_map(sexp_text)
1628        .map(str::to_owned)
1629        .collect())
1630}
1631
1632fn metadata_values<'a>(
1633    form: &'a Sexp,
1634    head: &str,
1635    position: Position,
1636) -> Result<&'a [Sexp], Error> {
1637    let list = list(form).ok_or_else(|| model_error("Expected metadata list", position))?;
1638    if list.first().and_then(sexp_text) != Some(head) {
1639        return Err(model_error("Unexpected metadata form", position));
1640    }
1641    Ok(&list[1..])
1642}
1643
1644fn parse_span(source: &str, span: &FormSpan) -> Result<Sexp, Error> {
1645    parse(span.text(source)?).map_err(|error| rebase_error(error, span))
1646}
1647
1648pub(crate) fn child<'a>(form: &'a Sexp, head: &str) -> Option<&'a Sexp> {
1649    list(form)?.iter().find(|candidate| {
1650        list(candidate)
1651            .and_then(|values| values.first())
1652            .and_then(sexp_text)
1653            == Some(head)
1654    })
1655}
1656
1657fn list(form: &Sexp) -> Option<&[Sexp]> {
1658    match form {
1659        Sexp::List(values) => Some(values),
1660        _ => None,
1661    }
1662}
1663
1664fn sexp_text(value: &Sexp) -> Option<&str> {
1665    match value {
1666        Sexp::Atom(value) | Sexp::Quoted(value) => Some(value),
1667        _ => None,
1668    }
1669}
1670
1671pub(crate) fn value_at(form: &Sexp, index: usize) -> Option<&str> {
1672    list(form)?.get(index).and_then(sexp_text)
1673}
1674
1675pub(crate) fn numeric_at(form: &Sexp, index: usize, position: Position) -> Result<f64, Error> {
1676    let value = list(form)
1677        .and_then(|values| values.get(index))
1678        .ok_or_else(|| model_error("Expected numeric coordinate", position))?;
1679    numeric_value(value, position)
1680}
1681
1682fn optional_numeric(form: &Sexp, index: usize, position: Position) -> Result<Option<f64>, Error> {
1683    list(form)
1684        .and_then(|values| values.get(index))
1685        .map(|value| numeric_value(value, position))
1686        .transpose()
1687}
1688
1689fn optional_numeric_at(
1690    form: Option<&Sexp>,
1691    index: usize,
1692    default: f64,
1693    position: Position,
1694) -> Result<f64, Error> {
1695    form.map(|value| optional_numeric(value, index, position))
1696        .transpose()
1697        .map(|value| value.flatten().unwrap_or(default))
1698}
1699
1700fn numeric_value(value: &Sexp, position: Position) -> Result<f64, Error> {
1701    match value {
1702        Sexp::Integer(value) => Ok(*value as f64),
1703        Sexp::Float(value) => Ok(*value),
1704        Sexp::Atom(value) => value
1705            .parse::<f64>()
1706            .map_err(|_| model_error("Expected numeric coordinate", position)),
1707        _ => Err(model_error("Expected numeric coordinate", position)),
1708    }
1709}
1710
1711fn finite_number(value: f64, position: Position) -> Result<f64, Error> {
1712    if value.is_finite() {
1713        Ok(value)
1714    } else {
1715        Err(model_error("Expected finite numeric value", position))
1716    }
1717}
1718
1719pub(crate) fn mm_to_nm(value: f64) -> Result<i64, Error> {
1720    let scaled = value * 1_000_000.0;
1721    if !scaled.is_finite()
1722        || scaled < JAVASCRIPT_SAFE_INTEGER_MIN as f64
1723        || scaled > JAVASCRIPT_SAFE_INTEGER_MAX as f64
1724    {
1725        return Err(model_error(
1726            "Coordinate exceeds JavaScript safe-integer range",
1727            Position::START,
1728        ));
1729    }
1730    Ok(scaled.round_ties_even() as i64)
1731}
1732
1733pub(crate) fn ensure_javascript_safe_integer(value: i64) -> Result<i64, Error> {
1734    if (JAVASCRIPT_SAFE_INTEGER_MIN..=JAVASCRIPT_SAFE_INTEGER_MAX).contains(&value) {
1735        Ok(value)
1736    } else {
1737        Err(model_error(
1738            "Document version exceeds JavaScript safe-integer range",
1739            Position::START,
1740        ))
1741    }
1742}
1743
1744fn root_flags(source: &str) -> Result<(bool, bool), Error> {
1745    let mut depth = 0usize;
1746    let mut locked = false;
1747    let mut placed = false;
1748    for token in Lexer::new(source) {
1749        let token = token?;
1750        match token.kind {
1751            TokenKind::Left => depth = depth.saturating_add(1),
1752            TokenKind::Right => depth = depth.saturating_sub(1),
1753            TokenKind::Atom if depth == 1 && token.lexeme == "locked" => locked = true,
1754            TokenKind::Atom if depth == 1 && token.lexeme == "placed" => placed = true,
1755            _ => {}
1756        }
1757    }
1758    Ok((locked, placed))
1759}
1760
1761fn rebase_error(mut error: Error, span: &FormSpan) -> Error {
1762    if let Some(position) = error.position {
1763        error.position = Some(Position {
1764            offset: span.range.start.saturating_add(position.offset),
1765            line: span
1766                .start
1767                .line
1768                .saturating_add(position.line.saturating_sub(1)),
1769            column: if position.line == 1 {
1770                span.start
1771                    .column
1772                    .saturating_add(position.column.saturating_sub(1))
1773            } else {
1774                position.column
1775            },
1776        });
1777    }
1778    error
1779}
1780
1781pub(crate) fn model_error(message: &'static str, position: Position) -> Error {
1782    Error::at(
1783        ErrorPhase::Tree,
1784        ErrorKind::UnexpectedToken,
1785        message,
1786        position,
1787    )
1788}
1789
1790pub(crate) fn limit_error() -> Error {
1791    Error::at(
1792        ErrorPhase::Tree,
1793        ErrorKind::ResourceLimit,
1794        "Footprint plotter operation exceeds configured limits",
1795        Position::START,
1796    )
1797}
1798
1799pub(crate) fn text_limit_error() -> Error {
1800    Error::at(
1801        ErrorPhase::Tree,
1802        ErrorKind::ResourceLimit,
1803        "Footprint plotter text exceeds max_text_bytes",
1804        Position::START,
1805    )
1806}
1807
1808fn metadata_limit_error() -> Error {
1809    Error::at(
1810        ErrorPhase::Tree,
1811        ErrorKind::ResourceLimit,
1812        "Footprint plotter metadata exceeds max_metadata_forms",
1813        Position::START,
1814    )
1815}
1816
1817fn geometry_limit_error() -> Error {
1818    Error::at(
1819        ErrorPhase::Tree,
1820        ErrorKind::ResourceLimit,
1821        "Footprint plotter geometry exceeds max_points",
1822        Position::START,
1823    )
1824}
1825
1826fn decomposition_limit_error(message: &'static str) -> Error {
1827    Error::at(
1828        ErrorPhase::Tree,
1829        ErrorKind::ResourceLimit,
1830        message,
1831        Position::START,
1832    )
1833}