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

kicad_monkey_core/pcb/
primary.rs

1//! Source-owned effective primary fields; original authored iterators stay raw.
2//! The ordered reducer returns existing records, never a domain/wire carrier.
3
4use super::*;
5use crate::sexpr::ErrorKind;
6
7mod batch;
8pub use batch::{PcbFootprintPrimaryBatch, PcbFootprintPrimaryFieldResults};
9
10const PRIMARY: [&str; 3] = ["Reference", "Value", "Description"];
11
12struct Event {
13    span: FormSpan,
14    legacy: bool,
15    scalar_alias: bool,
16    row: PcbFootprintProperty,
17}
18
19/// Exact source standard role; legacy ki_description is scalar-only before 20230620.
20pub fn footprint_primary_property_name(
21    name: &str,
22    file_version: i64,
23) -> Result<Option<&'static str>, Error> {
24    if let Some(&name) = PRIMARY.iter().find(|&&candidate| candidate == name) {
25        return Ok(Some(name));
26    }
27    if name == "ki_description" {
28        if file_version <= 0 {
29            return Err(capability(
30                "legacy description classification needs source version context",
31            ));
32        }
33        if file_version < 20230620 {
34            return Ok(Some("Description"));
35        }
36    }
37    Ok(None)
38}
39
40pub(crate) fn standalone_primary_property_name(
41    source: &str,
42    root: &FormSpan,
43    name: &str,
44    limits: PcbLimits,
45) -> Result<Option<&'static str>, Error> {
46    let fields = direct_children(source, root, limits.max_footprint_children, limits)?;
47    footprint_primary_property_name(
48        name,
49        optional_child_i64(source, &fields, "version")?.unwrap_or(0),
50    )
51}
52
53impl PcbView<'_> {
54    pub fn effective_footprint_primary_values(
55        &self,
56        footprint_index: usize,
57    ) -> Result<BTreeMap<String, String>, Error> {
58        Ok(events(self, footprint_index)?
59            .into_iter()
60            .map(|event| (event.row.name, event.row.value))
61            .collect())
62    }
63
64    pub fn effective_footprint_primary_fields(
65        &self,
66        footprint_index: usize,
67    ) -> Result<Vec<PcbFootprintProperty>, Error> {
68        let mut rows = Vec::new();
69        for name in PRIMARY {
70            if let Some(row) = self.effective_footprint_primary_field(footprint_index, name)? {
71                rows.push(row);
72            }
73        }
74        Ok(rows)
75    }
76
77    pub fn effective_footprint_primary_field(
78        &self,
79        footprint_index: usize,
80        name: &str,
81    ) -> Result<Option<PcbFootprintProperty>, Error> {
82        if !PRIMARY.contains(&name) {
83            return Err(capability(
84                "primary selector must be Reference, Value, or Description",
85            ));
86        }
87        if !self.selection.contains(PcbFamily::Footprints) {
88            return Err(capability(
89                "effective primary reading requires footprint source family",
90            ));
91        }
92        let indexed = self
93            .footprints
94            .get(footprint_index)
95            .ok_or_else(|| capability("primary footprint index is absent"))?;
96        let footprint = footprint_from_span(self.source, indexed, self.limits)?;
97        let version = self.metadata()?.version;
98        reduce(
99            self.source,
100            events(self, footprint_index)?,
101            &footprint,
102            Some(version),
103            name,
104            self.limits,
105        )
106    }
107}
108
109fn events(view: &PcbView<'_>, index: usize) -> Result<Vec<Event>, Error> {
110    let (properties, texts) = event_indices(view, index)?;
111    events_from_indexed(
112        view.source,
113        properties,
114        texts,
115        view.metadata()?.version,
116        view.limits,
117    )
118}
119
120fn event_indices<'view>(
121    view: &'view PcbView<'_>,
122    index: usize,
123) -> Result<(&'view [IndexedNestedForm], &'view [IndexedNestedForm]), Error> {
124    if !view.selection.contains(PcbFamily::Footprints) {
125        return Err(capability(
126            "effective primary reading requires footprint source family",
127        ));
128    }
129    if view.footprints.get(index).is_none() {
130        return Err(capability("primary footprint index is absent"));
131    }
132    if !view.selection.contains(PcbFamily::FootprintProperties)
133        || !view.selection.contains(PcbFamily::FootprintTexts)
134    {
135        return Err(capability(
136            "effective primary reading requires property and text source families",
137        ));
138    }
139    let start = view
140        .footprint_properties
141        .partition_point(|row| row.parent_index < index);
142    let end = view
143        .footprint_properties
144        .partition_point(|row| row.parent_index <= index);
145    let properties = &view.footprint_properties[start..end];
146    let start = view
147        .footprint_texts
148        .partition_point(|row| row.parent_index < index);
149    let end = view
150        .footprint_texts
151        .partition_point(|row| row.parent_index <= index);
152    Ok((properties, &view.footprint_texts[start..end]))
153}
154
155fn events_from_indexed(
156    source: &str,
157    properties: &[IndexedNestedForm],
158    texts: &[IndexedNestedForm],
159    version: i64,
160    limits: PcbLimits,
161) -> Result<Vec<Event>, Error> {
162    let mut events = Vec::new();
163    for indexed in properties {
164        let mut row = footprints::footprint_property_from_span(source, indexed, limits)?;
165        if let Some(name) = footprint_primary_property_name(&row.name, version)? {
166            let scalar_alias = row.name == "ki_description";
167            if scalar_alias
168                && (!direct_children(source, &indexed.span, limits.max_object_children, limits)?
169                    .is_empty()
170                    || bounded_scalar_values(source, &indexed.span, limits.max_object_children)?
171                        .len()
172                        != 2)
173            {
174                return Err(source_error(
175                    "legacy ki_description accepts only its scalar value",
176                    indexed.span.start,
177                ));
178            }
179            row.name = name.into();
180            validate_primary_leaves(source, &indexed.span, limits)?;
181            events.push(Event {
182                span: indexed.span.clone(),
183                legacy: false,
184                scalar_alias,
185                row,
186            });
187        }
188    }
189    for indexed in texts {
190        let row = footprints::footprint_text_from_span(source, indexed, limits)?;
191        let name = match row.kind.as_str() {
192            "reference" => "Reference",
193            "value" => "Value",
194            _ => continue,
195        };
196        validate_primary_leaves(source, &indexed.span, limits)?;
197        let fields = direct_children(source, &indexed.span, limits.max_object_children, limits)?;
198        events.push(Event {
199            span: indexed.span.clone(),
200            legacy: true,
201            scalar_alias: false,
202            row: PcbFootprintProperty {
203                footprint_index: row.footprint_index,
204                name: name.into(),
205                value: row.text,
206                at: row.at,
207                angle: row.angle,
208                layer: row.layer,
209                knockout: row.knockout,
210                hidden: row.hidden,
211                unlocked: row.unlocked,
212                graphical: child(&fields, "at").is_some() && child(&fields, "layer").is_some(),
213                effects: row.effects,
214                render_cache_range: row.render_cache_range,
215                uuid: row.uuid,
216                source_range: row.source_range,
217            },
218        });
219    }
220    events.sort_by_key(|event| event.span.range.start);
221    Ok(events)
222}
223
224pub(crate) fn standalone_primary_fields(
225    source: &str,
226    root: &FormSpan,
227    properties: &[FormSpan],
228    texts: &[FormSpan],
229    limits: PcbLimits,
230    name: &str,
231) -> Result<Option<PcbFootprintProperty>, Error> {
232    if !PRIMARY.contains(&name) {
233        return Err(capability(
234            "primary selector must be Reference, Value, or Description",
235        ));
236    }
237    let (events, footprint, version) = standalone_inputs(source, root, properties, texts, limits)?;
238    reduce(source, events, &footprint, version, name, limits)
239}
240
241pub(crate) fn standalone_primary_values(
242    source: &str,
243    root: &FormSpan,
244    properties: &[FormSpan],
245    texts: &[FormSpan],
246    limits: PcbLimits,
247) -> Result<BTreeMap<String, String>, Error> {
248    let (events, _, _) = standalone_inputs(source, root, properties, texts, limits)?;
249    Ok(events
250        .into_iter()
251        .map(|event| (event.row.name, event.row.value))
252        .collect())
253}
254
255fn standalone_inputs(
256    source: &str,
257    root: &FormSpan,
258    properties: &[FormSpan],
259    texts: &[FormSpan],
260    limits: PcbLimits,
261) -> Result<(Vec<Event>, PcbFootprint, Option<i64>), Error> {
262    let indexed = |spans: &[FormSpan]| {
263        spans
264            .iter()
265            .cloned()
266            .map(|span| IndexedNestedForm {
267                parent_index: 0,
268                span,
269            })
270            .collect::<Vec<_>>()
271    };
272    let fields = direct_children(source, root, limits.max_footprint_children, limits)?;
273    let version = optional_child_i64(source, &fields, "version")?.or(Some(0));
274    let events = events_from_indexed(
275        source,
276        &indexed(properties),
277        &indexed(texts),
278        version.unwrap_or(0),
279        limits,
280    )?;
281    let footprint = standalone_footprint_from_span(
282        source,
283        root,
284        limits,
285        StandaloneFootprintCounts {
286            properties: properties.len(),
287            texts: texts.len(),
288            graphics: 0,
289            text_boxes: 0,
290            pads: 0,
291            models: 0,
292            embedded_files: 0,
293        },
294    )?;
295    Ok((events, footprint, version))
296}
297
298#[allow(
299    clippy::cognitive_complexity,
300    clippy::too_many_lines,
301    reason = "primary footprint property reducer reconciles legacy fp_text and modern property events"
302)]
303fn reduce(
304    source: &str,
305    events: Vec<Event>,
306    footprint: &PcbFootprint,
307    version: Option<i64>,
308    name: &str,
309    limits: PcbLimits,
310) -> Result<Option<PcbFootprintProperty>, Error> {
311    let mut state: Option<PcbFootprintProperty> = None;
312    for event in events.into_iter().filter(|event| event.row.name == name) {
313        let incoming = event.row;
314        if event.scalar_alias {
315            if state
316                .as_ref()
317                .is_some_and(|row| row.render_cache_range.is_some())
318            {
319                return Err(capability(
320                    "inherited primary source cache has no qualified original input proof",
321                ));
322            }
323            let mut row = state.take().unwrap_or_else(|| incoming.clone());
324            row.name = incoming.name;
325            row.value = incoming.value;
326            row.source_range = incoming.source_range;
327            state = Some(row);
328            continue;
329        }
330        let fields = direct_children(source, &event.span, limits.max_object_children, limits)?;
331        let header = bounded_scalar_values(source, &event.span, limits.max_object_children)?;
332        unique_attributes(
333            &fields,
334            header.get(2..).unwrap_or_default(),
335            &[
336                "at",
337                "layer",
338                "hide",
339                "unlocked",
340                "effects",
341                "render_cache",
342                "uuid",
343            ],
344        )?;
345        for flag in header.get(2..).unwrap_or_default() {
346            if !matches!(token_string(flag).as_str(), "hide" | "unlocked") {
347                return Err(capability("unqualified primary field attribute"));
348            }
349        }
350        let prior = if event.legacy { None } else { state.take() };
351        let mut row = prior.clone().unwrap_or_else(|| incoming.clone());
352        row.name.clone_from(&incoming.name);
353        row.value.clone_from(&incoming.value);
354        let at = child(&fields, "at");
355        let layer = child(&fields, "layer");
356        let has_layout = at.is_some() && layer.is_some();
357        if prior.as_ref().is_some_and(|old| old.graphical) && !has_layout {
358            if at.is_none()
359                && (footprint.angle.unwrap_or(0.) != 0.
360                    || footprint.at_x.unwrap_or(0.) != 0.
361                    || footprint.at_y.unwrap_or(0.) != 0.)
362            {
363                return Err(capability(
364                    "primary partial placement requires qualified source frame replay",
365                ));
366            }
367        } else if prior.is_none() && !has_layout {
368            row.graphical = false;
369        }
370        if let Some(at) = at {
371            row.at = incoming.at;
372            row.angle =
373                footprints::footprint_text_position(source, std::slice::from_ref(at), limits)?.0[2];
374        } else {
375            row.angle = 0.;
376        }
377        if layer.is_some() {
378            row.layer.clone_from(&incoming.layer);
379            row.knockout |= incoming.knockout;
380        }
381        row.graphical |= has_layout;
382        row.unlocked = false;
383        if !event.legacy {
384            if version.is_none() && row.graphical {
385                return Err(capability(
386                    "primary property visibility needs source version context",
387                ));
388            }
389            row.hidden = version.is_some_and(|version| version < 20230620);
390        }
391        if has_flag(&header, "hide") {
392            row.hidden = true;
393        }
394        if has_flag(&header, "unlocked") {
395            row.unlocked = true;
396        }
397        let mut saw_effects = false;
398        for field in &fields {
399            match field.head.as_deref() {
400                Some("hide") => row.hidden = boolean(source, field, limits)?,
401                Some("unlocked") => row.unlocked = boolean(source, field, limits)?,
402                Some("at") => {
403                    if footprints::footprint_text_position(
404                        source,
405                        std::slice::from_ref(field),
406                        limits,
407                    )?
408                    .1
409                    {
410                        row.unlocked = true;
411                    }
412                }
413                Some("effects") => {
414                    if saw_effects {
415                        return Err(capability(
416                            "duplicate primary effects blocks are not qualified",
417                        ));
418                    }
419                    saw_effects = true;
420                    apply_effects(source, field, &incoming, &mut row, limits)?;
421                }
422                Some("layer" | "uuid" | "tstamp" | "render_cache") => {}
423                _ => return Err(capability("unqualified primary field attribute")),
424            }
425        }
426        if prior
427            .as_ref()
428            .is_some_and(|old| old.render_cache_range.is_some())
429            && incoming.render_cache_range.is_none()
430        {
431            return Err(capability(
432                "inherited primary source cache has no qualified original input proof",
433            ));
434        }
435        row.render_cache_range = incoming.render_cache_range;
436        if incoming.uuid.is_some() {
437            row.uuid = incoming.uuid;
438        }
439        row.source_range = incoming.source_range;
440        row.effects.hidden = row.hidden;
441        state = Some(row);
442    }
443    Ok(state)
444}
445
446fn boolean(source: &str, span: &FormSpan, limits: PcbLimits) -> Result<bool, Error> {
447    let values = bounded_scalar_values(source, span, limits.max_object_children)?;
448    let strict = span.head.as_deref() == Some("unlocked");
449    if values.len() > 1
450        || values
451            .first()
452            .is_some_and(|token| token.kind != TokenKind::Atom)
453    {
454        return Err(source_error(
455            "primary boolean requires yes or no",
456            span.start,
457        ));
458    }
459    match values.first().map(token_string).as_deref() {
460        None if !strict => Ok(true),
461        Some("yes") => Ok(true),
462        Some("no") => Ok(false),
463        Some("true") if !strict => Ok(true),
464        Some("false") if !strict => Ok(false),
465        _ => Err(source_error(
466            "primary boolean requires yes or no",
467            span.start,
468        )),
469    }
470}
471
472fn validate_primary_leaves(source: &str, span: &FormSpan, limits: PcbLimits) -> Result<(), Error> {
473    let header = bounded_scalar_values(source, span, limits.max_object_children)?;
474    if has_flag(header.get(2..).unwrap_or_default(), "unlocked") {
475        return Err(source_error(
476            "primary unlocked requires yes or no",
477            span.start,
478        ));
479    }
480    let mut pending = direct_children(source, span, limits.max_object_children, limits)?;
481    while let Some(leaf) = pending.pop() {
482        match leaf.head.as_deref() {
483            Some("effects" | "font") => {
484                if leaf.head.as_deref() == Some("font") {
485                    let header =
486                        bounded_scalar_values(source, &leaf, limits.max_text_font_children)?;
487                    if header.iter().any(|token| token_string(token) == "color") {
488                        return Err(source_error(
489                            "primary font color requires four numeric components",
490                            leaf.start,
491                        ));
492                    }
493                }
494                pending.extend(direct_children(
495                    source,
496                    &leaf,
497                    limits.max_object_children,
498                    limits,
499                )?);
500            }
501            Some("hide" | "unlocked" | "bold" | "italic") => {
502                boolean(source, &leaf, limits)?;
503            }
504            Some("at") => {
505                footprints::footprint_text_position(source, std::slice::from_ref(&leaf), limits)?;
506            }
507            Some("layer") => {
508                let values = bounded_scalar_values(source, &leaf, limits.max_object_children)?;
509                if !direct_children(source, &leaf, limits.max_object_children, limits)?.is_empty()
510                    || values.is_empty()
511                    || values.len() > 2
512                    || values.get(1).is_some_and(|token| {
513                        token.kind != TokenKind::Atom || token.lexeme != "knockout"
514                    })
515                {
516                    return Err(source_error(
517                        "primary layer has an invalid trailing token",
518                        leaf.start,
519                    ));
520                }
521            }
522            Some("color") => validate_primary_color(source, &leaf, limits)?,
523            Some("size" | "thickness" | "line_spacing") => {
524                let values = bounded_scalar_values(source, &leaf, limits.max_object_children)?;
525                let count = match leaf.head.as_deref() {
526                    Some("size") => 2,
527                    _ => 1,
528                };
529                if values.len() != count {
530                    return Err(source_error(
531                        "primary numeric leaf has invalid arity",
532                        leaf.start,
533                    ));
534                }
535                for index in 0..count {
536                    required_f64(
537                        values.get(index),
538                        "Expected finite primary numeric leaf",
539                        &leaf,
540                    )?;
541                }
542            }
543            _ => {} // Optional cache parsing retains its independently fallible source facts.
544        }
545    }
546    Ok(())
547}
548
549// Legacy Monkey text metadata/Plotter-IR accepts RGBA even though KiCad's PCB
550// parseEDA_TEXT grammar does not. Keep this read compatibility bounded and do
551// not normalize the retained Source color into a rendering color here.
552fn validate_primary_color(source: &str, leaf: &FormSpan, limits: PcbLimits) -> Result<(), Error> {
553    let values = bounded_scalar_values(source, leaf, limits.max_text_font_children)?;
554    if values.len() != 4
555        || !direct_children(source, leaf, limits.max_text_font_children, limits)?.is_empty()
556    {
557        return Err(source_error(
558            "primary font color requires four numeric components",
559            leaf.start,
560        ));
561    }
562    for value in &values[..3] {
563        required_i64(Some(value), "Expected integer primary color channel", leaf)?;
564    }
565    required_f64(values.get(3), "Expected finite primary color alpha", leaf)?;
566    Ok(())
567}
568
569#[allow(
570    clippy::too_many_lines,
571    reason = "text effects application preserves every authored font, justify, and hide attribute"
572)]
573fn apply_effects(
574    source: &str,
575    effects: &FormSpan,
576    incoming: &PcbFootprintProperty,
577    state: &mut PcbFootprintProperty,
578    limits: PcbLimits,
579) -> Result<(), Error> {
580    state.effects.justify.clear();
581    let header = bounded_scalar_values(source, effects, limits.max_text_effect_children)?;
582    if has_flag(&header, "hide") {
583        state.hidden = true;
584    }
585    let fields = direct_children(source, effects, limits.max_text_effect_children, limits)?;
586    unique_attributes(&fields, &header, &["font", "justify", "hide"])?;
587    let mut size = false;
588    let mut saw_font = false;
589    for field in &fields {
590        match field.head.as_deref() {
591            Some("font") => {
592                if saw_font {
593                    return Err(capability(
594                        "duplicate primary font blocks are not qualified",
595                    ));
596                }
597                saw_font = true;
598                let header = bounded_scalar_values(source, field, limits.max_text_font_children)?;
599                if has_flag(&header, "bold") {
600                    state.effects.font.bold = true;
601                }
602                if has_flag(&header, "italic") {
603                    state.effects.font.italic = true;
604                }
605                let font_fields =
606                    direct_children(source, field, limits.max_text_font_children, limits)?;
607                unique_attributes(
608                    &font_fields,
609                    &header,
610                    &[
611                        "face",
612                        "size",
613                        "thickness",
614                        "line_spacing",
615                        "color",
616                        "bold",
617                        "italic",
618                    ],
619                )?;
620                let mut seen = std::collections::HashSet::new();
621                for leaf in &font_fields {
622                    if !seen.insert(leaf.head.as_deref()) {
623                        return Err(capability(
624                            "duplicate primary font leaves are not qualified",
625                        ));
626                    }
627                    match leaf.head.as_deref() {
628                        Some("face") => state
629                            .effects
630                            .font
631                            .face
632                            .clone_from(&incoming.effects.font.face),
633                        Some("size") => {
634                            state.effects.font.size_x = incoming.effects.font.size_x;
635                            state.effects.font.size_y = incoming.effects.font.size_y;
636                            size = true;
637                        }
638                        Some("thickness") => {
639                            state.effects.font.thickness = incoming.effects.font.thickness
640                        }
641                        Some("line_spacing") => {
642                            state.effects.font.line_spacing = incoming.effects.font.line_spacing
643                        }
644                        Some("color") => state.effects.font.color = incoming.effects.font.color,
645                        Some("bold") => state.effects.font.bold = boolean(source, leaf, limits)?,
646                        Some("italic") => {
647                            state.effects.font.italic = boolean(source, leaf, limits)?
648                        }
649                        _ => return Err(capability("unqualified primary font attribute")),
650                    }
651                }
652            }
653            Some("justify") => {
654                let mut horizontal = None;
655                let mut vertical = None;
656                let mut mirror = false;
657                for token in bounded_scalar_values(source, field, limits.max_text_effect_children)?
658                {
659                    let value = token_string(&token);
660                    match value.as_str() {
661                        "left" | "right" => horizontal = Some(value),
662                        "top" | "bottom" => vertical = Some(value),
663                        "mirror" => mirror = true,
664                        _ => return Err(capability("unqualified primary justification")),
665                    }
666                }
667                state.effects.justify = horizontal
668                    .into_iter()
669                    .chain(vertical)
670                    .chain(mirror.then(|| "mirror".to_owned()))
671                    .collect();
672            }
673            Some("hide") => state.hidden = boolean(source, field, limits)?,
674            _ => return Err(capability("unqualified primary effect attribute")),
675        }
676    }
677    if !size {
678        state.effects.font.size_x = 1.524;
679        state.effects.font.size_y = 1.524;
680    }
681    state.effects.source_range = Some(effects.range.clone());
682    Ok(())
683}
684
685fn capability(message: &'static str) -> Error {
686    Error::build(ErrorKind::UnexpectedToken, message)
687}
688
689fn unique_attributes(
690    fields: &[FormSpan],
691    header: &[Token<'_>],
692    names: &[&str],
693) -> Result<(), Error> {
694    let mut seen = std::collections::HashSet::new();
695    for name in fields.iter().filter_map(|field| field.head.as_deref()) {
696        if names.contains(&name) && !seen.insert(name.to_owned()) {
697            return Err(capability("duplicate primary attributes are not qualified"));
698        }
699    }
700    for token in header {
701        let name = token_string(token);
702        if names.contains(&name.as_str()) && !seen.insert(name) {
703            return Err(capability("duplicate primary attributes are not qualified"));
704        }
705    }
706    Ok(())
707}