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

kicad_monkey_contracts/
lib.rs

1//! Generated transport types for KiCad Monkey operation boundaries.
2
3#![forbid(unsafe_code)]
4#![allow(
5    clippy::derivable_impls,
6    reason = "Typify emits explicit schema defaults in committed generated modules"
7)]
8
9mod board_plot_contract;
10mod compiled_graph_contract;
11mod font_bundle_contract;
12mod font_text_contract;
13pub mod generated;
14mod schematic_plot_contract;
15mod source_bundle_contract;
16
17pub use board_plot_contract::validate_board_plot_document;
18pub use compiled_graph_contract::{
19    CompiledGraphDecodeError, decode_compiled_schematic_graph_a0,
20    validate_compiled_schematic_graph_contract,
21};
22pub use font_bundle_contract::{
23    FontBundleLimits, FontResolutionLimits, ValidatedFontBundle, resolve_font_selection_contract,
24    validate_font_bundle_contract,
25};
26pub use font_text_contract::{validate_outline_vector_contract, validate_shaping_record_contract};
27pub use schematic_plot_contract::validate_schematic_plot_document;
28pub use source_bundle_contract::{
29    SourceBundleDecodeError, decode_source_bundle_manifest_a0,
30    validate_source_bundle_manifest_contract,
31};
32
33use generated::build_request::{Node, NodeKind, SExpressionBuildRequestA0};
34use generated::footprint_plot_document::{
35    CircleOperation, FlashPadCustomOperation, FootprintPlotDocumentA0, PlotterDrillRole,
36    PlotterOperation, TextOperation, ThickSegmentOperation,
37};
38use generated::symbol_plot_document::{
39    PlotterOperation as SymbolOperation, SymbolPlotDocumentA0, SymbolPlotRecord,
40};
41
42#[doc(hidden)]
43pub fn reject_present_render_cache_polygons<'de, D, T>(_: D) -> Result<T, D::Error>
44where
45    D: serde::Deserializer<'de>,
46{
47    Err(serde::de::Error::custom(
48        "cache-free producer text forbids render_cache_polygons",
49    ))
50}
51
52#[doc(hidden)]
53pub fn deserialize_present_optional_string<'de, D>(
54    deserializer: D,
55) -> Result<Option<String>, D::Error>
56where
57    D: serde::Deserializer<'de>,
58{
59    <String as serde::Deserialize>::deserialize(deserializer).map(Some)
60}
61
62#[doc(hidden)]
63pub fn deserialize_present_nonnull<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
64where
65    D: serde::Deserializer<'de>,
66    T: serde::Deserialize<'de>,
67{
68    <T as serde::Deserialize>::deserialize(deserializer).map(Some)
69}
70
71#[doc(hidden)]
72pub fn deserialize_required_nullable<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
73where
74    D: serde::Deserializer<'de>,
75    T: serde::Deserialize<'de>,
76{
77    <Option<T> as serde::Deserialize>::deserialize(deserializer)
78}
79
80#[doc(hidden)]
81pub fn reject_present_schematic_segment_layers<'de, D, T>(_: D) -> Result<T, D::Error>
82where
83    D: serde::Deserializer<'de>,
84{
85    Err(serde::de::Error::custom(
86        "schematic producer segments forbid layers",
87    ))
88}
89
90#[doc(hidden)]
91pub fn deserialize_present_nullable_string<'de, D>(
92    deserializer: D,
93) -> Result<Option<Option<String>>, D::Error>
94where
95    D: serde::Deserializer<'de>,
96{
97    <Option<String> as serde::Deserialize>::deserialize(deserializer).map(Some)
98}
99
100macro_rules! literal_kind_deserializer {
101    ($name:ident, $expected:literal) => {
102        #[doc(hidden)]
103        pub fn $name<'de, D>(deserializer: D) -> Result<String, D::Error>
104        where
105            D: serde::Deserializer<'de>,
106        {
107            let value = <String as serde::Deserialize>::deserialize(deserializer)?;
108            if value == $expected {
109                Ok(value)
110            } else {
111                Err(serde::de::Error::custom(concat!(
112                    "expected operation kind ",
113                    $expected
114                )))
115            }
116        }
117    };
118}
119
120literal_kind_deserializer!(deserialize_thick_segment_kind, "ThickSegment");
121literal_kind_deserializer!(deserialize_arc_three_point_kind, "ArcThreePoint");
122literal_kind_deserializer!(deserialize_circle_kind, "Circle");
123literal_kind_deserializer!(deserialize_rect_kind, "Rect");
124literal_kind_deserializer!(deserialize_plot_poly_kind, "PlotPoly");
125literal_kind_deserializer!(deserialize_bezier_curve_kind, "BezierCurve");
126literal_kind_deserializer!(deserialize_text_kind, "Text");
127literal_kind_deserializer!(deserialize_plot_image_kind, "PlotImage");
128literal_kind_deserializer!(deserialize_flash_pad_circle_kind, "FlashPadCircle");
129literal_kind_deserializer!(deserialize_flash_pad_oval_kind, "FlashPadOval");
130literal_kind_deserializer!(deserialize_flash_pad_rect_kind, "FlashPadRect");
131literal_kind_deserializer!(deserialize_flash_pad_round_rect_kind, "FlashPadRoundRect");
132literal_kind_deserializer!(deserialize_flash_pad_custom_kind, "FlashPadCustom");
133literal_kind_deserializer!(deserialize_flash_pad_trapez_kind, "FlashPadTrapez");
134literal_kind_deserializer!(deserialize_start_block_kind, "StartBlock");
135literal_kind_deserializer!(deserialize_end_block_kind, "EndBlock");
136literal_kind_deserializer!(deserialize_sheet_header_kind, "sheet_header");
137literal_kind_deserializer!(deserialize_wire_record_kind, "wire");
138literal_kind_deserializer!(deserialize_bus_record_kind, "bus");
139literal_kind_deserializer!(deserialize_bus_entry_record_kind, "bus_entry");
140literal_kind_deserializer!(deserialize_junction_record_kind, "junction");
141literal_kind_deserializer!(deserialize_no_connect_record_kind, "no_connect");
142literal_kind_deserializer!(deserialize_label_record_kind, "label");
143literal_kind_deserializer!(deserialize_global_label_record_kind, "global_label");
144literal_kind_deserializer!(
145    deserialize_hierarchical_label_record_kind,
146    "hierarchical_label"
147);
148literal_kind_deserializer!(deserialize_netclass_flag_record_kind, "netclass_flag");
149literal_kind_deserializer!(deserialize_text_record_kind, "text");
150literal_kind_deserializer!(deserialize_text_box_record_kind, "text_box");
151literal_kind_deserializer!(deserialize_graphic_polyline_record_kind, "graphic_polyline");
152literal_kind_deserializer!(deserialize_graphic_arc_record_kind, "graphic_arc");
153literal_kind_deserializer!(deserialize_graphic_circle_record_kind, "graphic_circle");
154literal_kind_deserializer!(
155    deserialize_graphic_rectangle_record_kind,
156    "graphic_rectangle"
157);
158literal_kind_deserializer!(deserialize_graphic_bezier_record_kind, "graphic_bezier");
159literal_kind_deserializer!(deserialize_rule_area_record_kind, "rule_area");
160literal_kind_deserializer!(deserialize_image_record_kind, "image");
161literal_kind_deserializer!(deserialize_table_record_kind, "table");
162literal_kind_deserializer!(deserialize_symbol_instance_record_kind, "symbol_instance");
163literal_kind_deserializer!(deserialize_symbol_overplot_record_kind, "symbol_overplot");
164literal_kind_deserializer!(deserialize_sheet_record_kind, "sheet");
165use std::fmt;
166
167/// Largest integer represented exactly by JavaScript's IEEE-754 `number`.
168pub const JAVASCRIPT_SAFE_INTEGER_MAX: i64 = 9_007_199_254_740_991;
169/// Smallest integer represented exactly by JavaScript's IEEE-754 `number`.
170pub const JAVASCRIPT_SAFE_INTEGER_MIN: i64 = -JAVASCRIPT_SAFE_INTEGER_MAX;
171/// KiCad's effective minimum plot pen width, in nanometres.
172pub const SCHEMATIC_DEFAULT_LINE_WIDTH_MIN_NM: i64 = 84_700;
173
174/// Integer guaranteed to remain exact across JSON and JavaScript/WASM boundaries.
175#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, serde::Serialize)]
176#[serde(transparent)]
177pub struct JavaScriptSafeInteger(i64);
178
179impl JavaScriptSafeInteger {
180    pub const fn get(self) -> i64 {
181        self.0
182    }
183}
184
185impl TryFrom<i64> for JavaScriptSafeInteger {
186    type Error = JavaScriptSafeIntegerError;
187
188    fn try_from(value: i64) -> Result<Self, Self::Error> {
189        if (JAVASCRIPT_SAFE_INTEGER_MIN..=JAVASCRIPT_SAFE_INTEGER_MAX).contains(&value) {
190            Ok(Self(value))
191        } else {
192            Err(JavaScriptSafeIntegerError { value })
193        }
194    }
195}
196
197impl From<JavaScriptSafeInteger> for i64 {
198    fn from(value: JavaScriptSafeInteger) -> Self {
199        value.0
200    }
201}
202
203impl<'de> serde::Deserialize<'de> for JavaScriptSafeInteger {
204    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
205    where
206        D: serde::Deserializer<'de>,
207    {
208        let value = i64::deserialize(deserializer)?;
209        Self::try_from(value).map_err(serde::de::Error::custom)
210    }
211}
212
213#[derive(Clone, Copy, Debug, Eq, PartialEq)]
214pub struct JavaScriptSafeIntegerError {
215    value: i64,
216}
217
218impl fmt::Display for JavaScriptSafeIntegerError {
219    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
220        write!(
221            formatter,
222            "{} is outside the JavaScript safe-integer range",
223            self.value
224        )
225    }
226}
227
228impl std::error::Error for JavaScriptSafeIntegerError {}
229
230/// Effective schematic default line width, already clamped for plotting.
231#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, serde::Serialize)]
232#[serde(transparent)]
233pub struct SchematicDefaultLineWidthNm(i64);
234
235impl SchematicDefaultLineWidthNm {
236    pub const fn get(self) -> i64 {
237        self.0
238    }
239}
240
241impl TryFrom<i64> for SchematicDefaultLineWidthNm {
242    type Error = SchematicDefaultLineWidthNmError;
243
244    fn try_from(value: i64) -> Result<Self, Self::Error> {
245        if (SCHEMATIC_DEFAULT_LINE_WIDTH_MIN_NM..=JAVASCRIPT_SAFE_INTEGER_MAX).contains(&value) {
246            Ok(Self(value))
247        } else {
248            Err(SchematicDefaultLineWidthNmError { value })
249        }
250    }
251}
252
253impl From<SchematicDefaultLineWidthNm> for i64 {
254    fn from(value: SchematicDefaultLineWidthNm) -> Self {
255        value.0
256    }
257}
258
259impl<'de> serde::Deserialize<'de> for SchematicDefaultLineWidthNm {
260    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
261    where
262        D: serde::Deserializer<'de>,
263    {
264        let value = i64::deserialize(deserializer)?;
265        Self::try_from(value).map_err(serde::de::Error::custom)
266    }
267}
268
269#[derive(Clone, Copy, Debug, Eq, PartialEq)]
270pub struct SchematicDefaultLineWidthNmError {
271    value: i64,
272}
273
274impl fmt::Display for SchematicDefaultLineWidthNmError {
275    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
276        write!(
277            formatter,
278            "{} is outside the effective schematic line-width range",
279            self.value
280        )
281    }
282}
283
284impl std::error::Error for SchematicDefaultLineWidthNmError {}
285
286/// Finite nonnegative floating-point value used for governed comparison tolerances.
287#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize)]
288#[serde(transparent)]
289pub struct NonNegativeFiniteFloat(f64);
290
291impl NonNegativeFiniteFloat {
292    pub const fn get(self) -> f64 {
293        self.0
294    }
295}
296
297impl TryFrom<f64> for NonNegativeFiniteFloat {
298    type Error = NonNegativeFiniteFloatError;
299
300    fn try_from(value: f64) -> Result<Self, Self::Error> {
301        if value.is_finite() && value >= 0.0 {
302            Ok(Self(value))
303        } else {
304            Err(NonNegativeFiniteFloatError { value })
305        }
306    }
307}
308
309impl<'de> serde::Deserialize<'de> for NonNegativeFiniteFloat {
310    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
311    where
312        D: serde::Deserializer<'de>,
313    {
314        let value = f64::deserialize(deserializer)?;
315        Self::try_from(value).map_err(serde::de::Error::custom)
316    }
317}
318
319#[derive(Clone, Copy, Debug, PartialEq)]
320pub struct NonNegativeFiniteFloatError {
321    value: f64,
322}
323
324impl fmt::Display for NonNegativeFiniteFloatError {
325    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
326        write!(
327            formatter,
328            "{} is not a finite nonnegative number",
329            self.value
330        )
331    }
332}
333
334impl std::error::Error for NonNegativeFiniteFloatError {}
335
336/// Finite float64 value used by programmatically constructed text DTOs.
337#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize)]
338#[serde(transparent)]
339pub struct FiniteFloat(f64);
340
341impl FiniteFloat {
342    pub const fn get(self) -> f64 {
343        self.0
344    }
345}
346
347impl TryFrom<f64> for FiniteFloat {
348    type Error = FiniteFloatError;
349
350    fn try_from(value: f64) -> Result<Self, Self::Error> {
351        if value.is_finite() {
352            Ok(Self(value))
353        } else {
354            Err(FiniteFloatError { value })
355        }
356    }
357}
358
359impl<'de> serde::Deserialize<'de> for FiniteFloat {
360    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
361    where
362        D: serde::Deserializer<'de>,
363    {
364        let value = f64::deserialize(deserializer)?;
365        Self::try_from(value).map_err(serde::de::Error::custom)
366    }
367}
368
369#[derive(Clone, Copy, Debug, PartialEq)]
370pub struct FiniteFloatError {
371    value: f64,
372}
373
374impl fmt::Display for FiniteFloatError {
375    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
376        write!(formatter, "{} is not finite", self.value)
377    }
378}
379
380impl std::error::Error for FiniteFloatError {}
381
382/// Strictly positive OpenType units-per-em transport value.
383#[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Serialize)]
384#[serde(transparent)]
385pub struct PositiveU32(u32);
386
387impl PositiveU32 {
388    pub const fn get(self) -> u32 {
389        self.0
390    }
391}
392
393impl TryFrom<u32> for PositiveU32 {
394    type Error = PositiveU32Error;
395
396    fn try_from(value: u32) -> Result<Self, Self::Error> {
397        if value > 0 {
398            Ok(Self(value))
399        } else {
400            Err(PositiveU32Error)
401        }
402    }
403}
404
405impl<'de> serde::Deserialize<'de> for PositiveU32 {
406    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
407    where
408        D: serde::Deserializer<'de>,
409    {
410        let value = u32::deserialize(deserializer)?;
411        Self::try_from(value).map_err(serde::de::Error::custom)
412    }
413}
414
415#[derive(Clone, Copy, Debug, Eq, PartialEq)]
416pub struct PositiveU32Error;
417
418impl fmt::Display for PositiveU32Error {
419    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
420        formatter.write_str("value must be greater than zero")
421    }
422}
423
424impl std::error::Error for PositiveU32Error {}
425
426/// Nonempty stable ASCII identifier for font entries and oracle cases.
427#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, serde::Serialize)]
428#[serde(transparent)]
429pub struct StableTextId(String);
430
431impl StableTextId {
432    pub fn as_str(&self) -> &str {
433        &self.0
434    }
435}
436
437impl std::ops::Deref for StableTextId {
438    type Target = str;
439
440    fn deref(&self) -> &Self::Target {
441        self.as_str()
442    }
443}
444
445impl fmt::Display for StableTextId {
446    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
447        formatter.write_str(self.as_str())
448    }
449}
450
451impl std::str::FromStr for StableTextId {
452    type Err = StableTextIdError;
453
454    fn from_str(value: &str) -> Result<Self, Self::Err> {
455        if valid_stable_text_id(value) {
456            Ok(Self(value.to_owned()))
457        } else {
458            Err(StableTextIdError)
459        }
460    }
461}
462
463impl<'de> serde::Deserialize<'de> for StableTextId {
464    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
465    where
466        D: serde::Deserializer<'de>,
467    {
468        let value = String::deserialize(deserializer)?;
469        value.parse().map_err(serde::de::Error::custom)
470    }
471}
472
473fn valid_stable_text_id(value: &str) -> bool {
474    let mut bytes = value.bytes();
475    bytes
476        .next()
477        .is_some_and(|byte| byte.is_ascii_alphanumeric())
478        && bytes
479            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-'))
480}
481
482#[derive(Clone, Copy, Debug, Eq, PartialEq)]
483pub struct StableTextIdError;
484
485impl fmt::Display for StableTextIdError {
486    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
487        formatter.write_str("value is not a stable text identifier")
488    }
489}
490
491impl std::error::Error for StableTextIdError {}
492
493/// Validated, payload-exclusive generic node ready for conversion by adapters.
494#[derive(Clone, Debug, PartialEq)]
495pub enum ValidatedNode {
496    List(Vec<Self>),
497    Atom(String),
498    Quoted(String),
499    Integer(i64),
500    Float(f64),
501}
502
503/// A semantically validated build request. KiCad builds S-expressions of any
504/// size, so the request carries no ceilings (#612).
505#[derive(Clone, Debug, PartialEq)]
506pub struct ValidatedBuildRequest {
507    pub root: ValidatedNode,
508}
509
510/// Stable semantic contract validation failure.
511#[derive(Clone, Debug, Eq, PartialEq)]
512pub struct ValidationError {
513    pub code: &'static str,
514    pub path: String,
515    pub message: &'static str,
516}
517
518impl fmt::Display for ValidationError {
519    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
520        write!(
521            formatter,
522            "{} at {}: {}",
523            self.code, self.path, self.message
524        )
525    }
526}
527
528impl std::error::Error for ValidationError {}
529
530/// The text engine's contract failures keep their code, path and message.
531impl From<cad_text_realization::ValidationError> for ValidationError {
532    fn from(error: cad_text_realization::ValidationError) -> Self {
533        Self {
534            code: error.code,
535            path: error.path,
536            message: error.message,
537        }
538    }
539}
540
541/// Enforce identity and the `Node.kind` payload union.
542pub fn validate_build_request(
543    request: SExpressionBuildRequestA0,
544) -> Result<ValidatedBuildRequest, ValidationError> {
545    if request.type_ != "kicad_monkey.sexpr_build.request" || request.version != "a0" {
546        return Err(validation_error(
547            "unsupported_contract",
548            "$",
549            "unsupported S-expression build contract identity",
550        ));
551    }
552    let root = validate_node(request.root, "$.root".to_owned())?;
553    Ok(ValidatedBuildRequest { root })
554}
555
556/// Enforce the cross-field semantics of shared graphical and drill operations.
557pub fn validate_footprint_plot_document(
558    document: &FootprintPlotDocumentA0,
559) -> Result<(), ValidationError> {
560    if document.schema != "kicad.plotter_ir.a0"
561        || document.source_kind != "MOD"
562        || document.coordinate_space.unit != "nm"
563        || document.coordinate_space.y_axis != "down"
564        || document.records.len() != 1
565    {
566        return Err(validation_error(
567            "invalid_footprint_document",
568            "$".to_owned(),
569            "footprint plot documents require canonical identity, coordinates, and one record",
570        ));
571    }
572    let mut total_operations = 0usize;
573    for (record_index, record) in document.records.iter().enumerate() {
574        if record.kind != "footprint" || record.object_id != record.name {
575            return Err(validation_error(
576                "invalid_footprint_record",
577                format!("$.records[{record_index}]"),
578                "footprint records require kind=footprint and object_id=name",
579            ));
580        }
581        if record.operation_count as usize != record.operations.len() {
582            return Err(validation_error(
583                "operation_count_mismatch",
584                format!("$.records[{record_index}].operation_count"),
585                "operation_count must equal the operation array length",
586            ));
587        }
588        total_operations = total_operations.saturating_add(record.operations.len());
589        for (operation_index, operation) in record.operations.iter().enumerate() {
590            let path = format!("$.records[{record_index}].operations[{operation_index}]");
591            let expected_index = u32::try_from(operation_index).map_err(|_| {
592                validation_error(
593                    "operation_index_mismatch",
594                    format!("{path}.index"),
595                    "operation index exceeds the contract range",
596                )
597            })?;
598            validate_footprint_operation(operation, expected_index, path)?;
599        }
600    }
601    if document.total_operations as usize != total_operations {
602        return Err(validation_error(
603            "operation_count_mismatch",
604            "$.total_operations",
605            "total_operations must equal all record operation counts",
606        ));
607    }
608    Ok(())
609}
610
611fn validate_footprint_operation_header(
612    actual_index: u32,
613    actual_kind: &str,
614    expected_index: u32,
615    expected_kind: &str,
616    path: &str,
617) -> Result<(), ValidationError> {
618    if actual_kind != expected_kind {
619        return Err(validation_error(
620            "invalid_footprint_operation",
621            format!("{path}.kind"),
622            "operation kind must match its structural variant",
623        ));
624    }
625    if actual_index != expected_index {
626        return Err(validation_error(
627            "operation_index_mismatch",
628            format!("{path}.index"),
629            "operation index must equal its position in the record",
630        ));
631    }
632    Ok(())
633}
634
635macro_rules! validate_footprint_header {
636    ($value:expr, $index:expr, $kind:literal, $path:expr) => {
637        validate_footprint_operation_header($value.index, &$value.kind, $index, $kind, $path)?
638    };
639}
640
641fn validate_footprint_operation(
642    operation: &PlotterOperation,
643    expected_index: u32,
644    path: String,
645) -> Result<(), ValidationError> {
646    match operation {
647        PlotterOperation::TextOperation(operation) => {
648            validate_footprint_header!(operation, expected_index, "Text", &path);
649            validate_footprint_text(operation, path)
650        }
651        PlotterOperation::ThickSegmentOperation(operation) => {
652            validate_footprint_header!(operation, expected_index, "ThickSegment", &path);
653            validate_shared_segment(operation, path)
654        }
655        PlotterOperation::CircleOperation(operation) => {
656            validate_footprint_header!(operation, expected_index, "Circle", &path);
657            validate_shared_circle(operation, path)
658        }
659        _ => validate_footprint_static_operation(operation, expected_index, path),
660    }
661}
662
663fn validate_footprint_text(operation: &TextOperation, path: String) -> Result<(), ValidationError> {
664    require_layer(operation.layer.as_deref(), path.clone())?;
665    if operation.kind != "Text"
666        || operation.context.is_some()
667        || operation.mirror == Some(false)
668        || operation.text_as_polygons.is_some()
669        || operation.polyline_per_segment.is_some()
670        || operation.knockout.is_some()
671        || !operation.render_cache_polygons.is_empty()
672        || operation.render_cache.is_some()
673        || operation.render_cache_source.is_some()
674        || operation.render_cache_exact.is_some()
675    {
676        return Err(validation_error(
677            "invalid_footprint_text",
678            path,
679            "standalone footprint Text operations require a layer, an absent-or-true mirror marker, and cache-free canonical state",
680        ));
681    }
682    Ok(())
683}
684
685fn validate_footprint_static_operation(
686    operation: &PlotterOperation,
687    expected_index: u32,
688    path: String,
689) -> Result<(), ValidationError> {
690    match operation {
691        PlotterOperation::ArcThreePointOperation(value) => {
692            validate_footprint_header!(value, expected_index, "ArcThreePoint", &path);
693            require_layer(value.layer.as_deref(), path)
694        }
695        PlotterOperation::RectOperation(value) => {
696            validate_footprint_header!(value, expected_index, "Rect", &path);
697            require_layer(value.layer.as_deref(), path)
698        }
699        PlotterOperation::PlotPolyOperation(value) => {
700            validate_footprint_header!(value, expected_index, "PlotPoly", &path);
701            require_layer(value.layer.as_deref(), path)
702        }
703        PlotterOperation::BezierCurveOperation(value) => {
704            validate_footprint_header!(value, expected_index, "BezierCurve", &path);
705            require_layer(value.layer.as_deref(), path)
706        }
707        _ => validate_footprint_pad_operation(operation, expected_index, path),
708    }
709}
710
711fn validate_footprint_pad_operation(
712    operation: &PlotterOperation,
713    expected_index: u32,
714    path: String,
715) -> Result<(), ValidationError> {
716    match operation {
717        PlotterOperation::FlashPadCircleOperation(value) => {
718            validate_footprint_header!(value, expected_index, "FlashPadCircle", &path);
719            // The shared flash-circle model carries optional via roles for the
720            // board document; footprint pads keep the pad-margin state.
721            if value.mask_margin_nm.is_none() || value.role.is_some() {
722                return Err(validation_error(
723                    "invalid_pad_operation",
724                    path,
725                    "footprint flash circles require mask_margin_nm and no via role",
726                ));
727            }
728            require_layers(&value.layers, path)
729        }
730        PlotterOperation::FlashPadOvalOperation(value) => {
731            validate_footprint_header!(value, expected_index, "FlashPadOval", &path);
732            require_layers(&value.layers, path)
733        }
734        PlotterOperation::FlashPadRectOperation(value) => {
735            validate_footprint_header!(value, expected_index, "FlashPadRect", &path);
736            require_layers(&value.layers, path)
737        }
738        PlotterOperation::FlashPadRoundRectOperation(value) => {
739            validate_footprint_header!(value, expected_index, "FlashPadRoundRect", &path);
740            require_layers(&value.layers, path)
741        }
742        PlotterOperation::FlashPadCustomOperation(value) => {
743            validate_footprint_header!(value, expected_index, "FlashPadCustom", &path);
744            validate_custom_pad(value, path)
745        }
746        PlotterOperation::FlashPadTrapezOperation(value) => {
747            validate_footprint_header!(value, expected_index, "FlashPadTrapez", &path);
748            require_layers(&value.layers, path)
749        }
750        _ => Err(validation_error(
751            "invalid_footprint_operation",
752            path,
753            "operation is outside the footprint producer contract",
754        )),
755    }
756}
757
758/// Enforce identity, record counts, indices, and producer-specific symbol states.
759pub fn validate_symbol_plot_document(
760    document: &SymbolPlotDocumentA0,
761) -> Result<(), ValidationError> {
762    if document.schema != "kicad.plotter_ir.a0"
763        || document.source_kind != "SYM"
764        || document.coordinate_space.unit != "nm"
765        || document.coordinate_space.y_axis != "down"
766    {
767        return Err(validation_error(
768            "invalid_symbol_document",
769            "$",
770            "symbol plot documents require canonical identity and coordinates",
771        ));
772    }
773    if !matches!(
774        document.records.first(),
775        Some(SymbolPlotRecord::SymbolHeaderPlotRecord(_))
776    ) {
777        return Err(validation_error(
778            "missing_symbol_header",
779            "$.records[0]",
780            "the first symbol record must be the lib_symbol header",
781        ));
782    }
783    let mut total_operations = 0usize;
784    for (record_index, record) in document.records.iter().enumerate() {
785        let (declared, operations) = match record {
786            SymbolPlotRecord::SymbolHeaderPlotRecord(record) => {
787                if record_index != 0
788                    || record.kind != "lib_symbol"
789                    || record.object_id != record.name
790                    || record.operation_count != 0
791                    || !record.operations.is_empty()
792                {
793                    return Err(validation_error(
794                        "invalid_symbol_header",
795                        format!("$.records[{record_index}]"),
796                        "lib_symbol header operations must be empty",
797                    ));
798                }
799                (record.operation_count, &record.operations)
800            }
801            SymbolPlotRecord::LibSubsymbolPlotRecord(record) => {
802                if record.kind != "lib_subsymbol" || record.object_id.is_empty() {
803                    return Err(validation_error(
804                        "invalid_symbol_record",
805                        format!("$.records[{record_index}]"),
806                        "subsymbol records require kind=lib_subsymbol and an object_id",
807                    ));
808                }
809                (record.operation_count, &record.operations)
810            }
811        };
812        if declared as usize != operations.len() {
813            return Err(validation_error(
814                "operation_count_mismatch",
815                format!("$.records[{record_index}].operation_count"),
816                "operation_count must equal the operation array length",
817            ));
818        }
819        total_operations = total_operations.saturating_add(operations.len());
820        for (operation_index, operation) in operations.iter().enumerate() {
821            let path = format!("$.records[{record_index}].operations[{operation_index}]");
822            let expected_index = u32::try_from(
823                total_operations
824                    .saturating_sub(operations.len())
825                    .saturating_add(operation_index),
826            )
827            .map_err(|_| {
828                validation_error(
829                    "operation_index_mismatch",
830                    format!("{path}.index"),
831                    "operation index exceeds the contract range",
832                )
833            })?;
834            validate_symbol_operation(operation, expected_index, path)?;
835        }
836    }
837    if document.total_operations as usize != total_operations {
838        return Err(validation_error(
839            "operation_count_mismatch",
840            "$.total_operations",
841            "total_operations must equal all record operation counts",
842        ));
843    }
844    Ok(())
845}
846
847fn validate_symbol_operation(
848    operation: &SymbolOperation,
849    expected_index: u32,
850    path: String,
851) -> Result<(), ValidationError> {
852    macro_rules! require_header {
853        ($value:expr, $kind:literal) => {
854            validate_symbol_operation_header(
855                $value.index,
856                &$value.kind,
857                expected_index,
858                $kind,
859                &path,
860            )?
861        };
862    }
863    match operation {
864        SymbolOperation::ArcThreePointOperation(value) => {
865            require_header!(value, "ArcThreePoint");
866            require_symbol_layer_free(value.layer.as_deref(), path)
867        }
868        SymbolOperation::RectOperation(value) => {
869            require_header!(value, "Rect");
870            require_symbol_layer_free(value.layer.as_deref(), path)
871        }
872        SymbolOperation::PlotPolyOperation(value) => {
873            require_header!(value, "PlotPoly");
874            require_symbol_layer_free(value.layer.as_deref(), path)
875        }
876        SymbolOperation::BezierCurveOperation(value) => {
877            require_header!(value, "BezierCurve");
878            require_symbol_layer_free(value.layer.as_deref(), path)
879        }
880        SymbolOperation::CircleOperation(value) => {
881            require_header!(value, "Circle");
882            if symbol_circle_is_layer_free(value) {
883                Ok(())
884            } else {
885                invalid_symbol_operation(path)
886            }
887        }
888        SymbolOperation::TextOperation(value) => {
889            require_header!(value, "Text");
890            validate_symbol_text(value, path)
891        }
892        _ => invalid_symbol_operation(path),
893    }
894}
895
896fn validate_symbol_operation_header(
897    actual_index: u32,
898    actual_kind: &str,
899    expected_index: u32,
900    expected_kind: &str,
901    path: &str,
902) -> Result<(), ValidationError> {
903    if actual_kind != expected_kind {
904        return Err(validation_error(
905            "invalid_symbol_operation",
906            format!("{path}.kind"),
907            "operation kind must match its structural variant",
908        ));
909    }
910    if actual_index != expected_index {
911        return Err(validation_error(
912            "operation_index_mismatch",
913            format!("{path}.index"),
914            "operation index must equal its global position",
915        ));
916    }
917    Ok(())
918}
919
920fn require_symbol_layer_free(layer: Option<&str>, path: String) -> Result<(), ValidationError> {
921    if layer.is_none() {
922        Ok(())
923    } else {
924        invalid_symbol_operation(path)
925    }
926}
927
928fn validate_symbol_text(
929    operation: &generated::symbol_plot_document::TextOperation,
930    path: String,
931) -> Result<(), ValidationError> {
932    if operation.layer.is_none()
933        && operation.context.is_none()
934        && operation.mirror.is_none()
935        && operation.text_as_polygons.is_none()
936        && operation.polyline_per_segment.is_none()
937        && operation.knockout.is_none()
938        && operation.render_cache_polygons.is_empty()
939        && operation.render_cache.is_none()
940        && operation.render_cache_source.is_none()
941        && operation.render_cache_exact.is_none()
942    {
943        Ok(())
944    } else {
945        Err(validation_error(
946            "invalid_symbol_text",
947            path,
948            "symbol Text operations require layer-free, cache-free canonical state",
949        ))
950    }
951}
952
953fn invalid_symbol_operation(path: String) -> Result<(), ValidationError> {
954    Err(validation_error(
955        "invalid_symbol_operation",
956        path,
957        "symbol records accept only canonical layer-free geometry and Text",
958    ))
959}
960
961fn symbol_circle_is_layer_free(value: &generated::symbol_plot_document::CircleOperation) -> bool {
962    value.layer.is_none()
963        && value.role.is_none()
964        && value.layers.is_empty()
965        && value.mask_margin_nm.is_none()
966        && value.pad_size_x_nm.is_none()
967        && value.pad_size_y_nm.is_none()
968}
969
970fn validate_custom_pad(
971    operation: &FlashPadCustomOperation,
972    path: String,
973) -> Result<(), ValidationError> {
974    require_layers(&operation.layers, path.clone())?;
975    if !operation.polygon_widths_nm.is_empty()
976        && operation.polygon_widths_nm.len() != operation.polygons.len()
977    {
978        return Err(validation_error(
979            "polygon_width_count_mismatch",
980            format!("{path}.polygon_widths_nm"),
981            "non-empty polygon_widths_nm must contain one width per polygon",
982        ));
983    }
984    Ok(())
985}
986
987fn validate_shared_segment(
988    operation: &ThickSegmentOperation,
989    path: String,
990) -> Result<(), ValidationError> {
991    if operation.stroke_color.is_some() {
992        return Err(validation_error(
993            "invalid_segment_color",
994            format!("{path}.stroke_color"),
995            "standalone footprint segments do not emit stroke_color",
996        ));
997    }
998    validate_graphic_or_drill(
999        operation.layer.as_deref(),
1000        operation.role,
1001        &operation.layers,
1002        operation.mask_margin_nm.is_some(),
1003        operation.pad_size_x_nm.is_some(),
1004        operation.pad_size_y_nm.is_some(),
1005        path,
1006    )
1007}
1008
1009fn validate_shared_circle(
1010    operation: &CircleOperation,
1011    path: String,
1012) -> Result<(), ValidationError> {
1013    validate_graphic_or_drill(
1014        operation.layer.as_deref(),
1015        operation.role,
1016        &operation.layers,
1017        operation.mask_margin_nm.is_some(),
1018        operation.pad_size_x_nm.is_some(),
1019        operation.pad_size_y_nm.is_some(),
1020        path,
1021    )
1022}
1023
1024#[allow(
1025    clippy::too_many_arguments,
1026    reason = "the validator receives the complete shared graphic/drill state as separate fields"
1027)]
1028fn validate_graphic_or_drill(
1029    layer: Option<&str>,
1030    role: Option<PlotterDrillRole>,
1031    layers: &[String],
1032    has_mask_margin: bool,
1033    has_pad_size_x: bool,
1034    has_pad_size_y: bool,
1035    path: String,
1036) -> Result<(), ValidationError> {
1037    match role {
1038        None if layer.is_some()
1039            && layers.is_empty()
1040            && !has_mask_margin
1041            && !has_pad_size_x
1042            && !has_pad_size_y =>
1043        {
1044            Ok(())
1045        }
1046        Some(PlotterDrillRole::PadDrill)
1047            if layer.is_none()
1048                && !layers.is_empty()
1049                && !has_mask_margin
1050                && !has_pad_size_x
1051                && !has_pad_size_y =>
1052        {
1053            Ok(())
1054        }
1055        Some(PlotterDrillRole::NpthHole)
1056            if layer.is_none()
1057                && !layers.is_empty()
1058                && has_mask_margin
1059                && has_pad_size_x
1060                && has_pad_size_y =>
1061        {
1062            Ok(())
1063        }
1064        _ => Err(validation_error(
1065            "conflicting_plotter_fields",
1066            path,
1067            "circle/segment must be one complete graphic, pad-drill, or NPTH variant",
1068        )),
1069    }
1070}
1071
1072fn require_layers(layers: &[String], path: String) -> Result<(), ValidationError> {
1073    if layers.is_empty() {
1074        Err(validation_error(
1075            "missing_layers",
1076            path,
1077            "pad flash operations require at least one layer",
1078        ))
1079    } else {
1080        Ok(())
1081    }
1082}
1083
1084fn require_layer(layer: Option<&str>, path: String) -> Result<(), ValidationError> {
1085    if layer.is_some_and(|value| !value.is_empty()) {
1086        Ok(())
1087    } else {
1088        Err(validation_error(
1089            "missing_layer",
1090            path,
1091            "footprint graphic operations require a layer",
1092        ))
1093    }
1094}
1095
1096#[allow(
1097    clippy::too_many_lines,
1098    reason = "pre-standard recursive union validator retained under the structural ratchet"
1099)]
1100fn validate_node(node: Node, path: String) -> Result<ValidatedNode, ValidationError> {
1101    let Node {
1102        children,
1103        float,
1104        integer,
1105        kind,
1106        text,
1107    } = node;
1108    match kind {
1109        NodeKind::List => {
1110            require_absent(
1111                &path,
1112                text.is_none() && integer.is_none() && float.is_none(),
1113            )?;
1114            let mut validated = Vec::with_capacity(children.len());
1115            for (index, child) in children.into_iter().enumerate() {
1116                validated.push(validate_node(child, format!("{path}.children[{index}]"))?);
1117            }
1118            Ok(ValidatedNode::List(validated))
1119        }
1120        NodeKind::Atom | NodeKind::Quoted => {
1121            require_absent(
1122                &path,
1123                children.is_empty() && integer.is_none() && float.is_none(),
1124            )?;
1125            let text = text.ok_or_else(|| {
1126                validation_error(
1127                    "missing_payload",
1128                    &path,
1129                    "text payload is required for this kind",
1130                )
1131            })?;
1132            Ok(if kind == NodeKind::Atom {
1133                ValidatedNode::Atom(text)
1134            } else {
1135                ValidatedNode::Quoted(text)
1136            })
1137        }
1138        NodeKind::Integer => {
1139            require_absent(
1140                &path,
1141                children.is_empty() && text.is_none() && float.is_none(),
1142            )?;
1143            let integer = integer.ok_or_else(|| {
1144                validation_error(
1145                    "missing_payload",
1146                    &path,
1147                    "integer payload is required for this kind",
1148                )
1149            })?;
1150            let value = integer.parse::<i64>().map_err(|_| {
1151                validation_error(
1152                    "invalid_integer",
1153                    &path,
1154                    "integer payload must fit signed 64-bit decimal",
1155                )
1156            })?;
1157            Ok(ValidatedNode::Integer(value))
1158        }
1159        NodeKind::Float => {
1160            require_absent(
1161                &path,
1162                children.is_empty() && text.is_none() && integer.is_none(),
1163            )?;
1164            let value = float.ok_or_else(|| {
1165                validation_error(
1166                    "missing_payload",
1167                    &path,
1168                    "float payload is required for this kind",
1169                )
1170            })?;
1171            if !value.is_finite() {
1172                return Err(validation_error(
1173                    "invalid_float",
1174                    path,
1175                    "float payload must be finite",
1176                ));
1177            }
1178            Ok(ValidatedNode::Float(value))
1179        }
1180    }
1181}
1182
1183fn require_absent(path: &str, valid: bool) -> Result<(), ValidationError> {
1184    if valid {
1185        Ok(())
1186    } else {
1187        Err(validation_error(
1188            "conflicting_payload",
1189            path,
1190            "node contains payload fields not allowed by its kind",
1191        ))
1192    }
1193}
1194
1195pub(crate) fn validation_error(
1196    code: &'static str,
1197    path: impl Into<String>,
1198    message: &'static str,
1199) -> ValidationError {
1200    ValidationError {
1201        code,
1202        path: path.into(),
1203        message,
1204    }
1205}