1use super::*;
8
9#[derive(Clone, Debug, Eq, PartialEq)]
10pub struct PcbZoneKeepout {
11 pub tracks: String,
13 pub vias: String,
14 pub pads: String,
15 pub copperpour: String,
16 pub footprints: String,
17 pub has_tracks: bool,
18 pub has_vias: bool,
19 pub has_pads: bool,
20 pub has_copperpour: bool,
21 pub has_footprints: bool,
22}
23
24#[derive(Clone, Copy, Debug, Eq, PartialEq)]
25pub enum PcbZonePlacementSource {
26 SheetName,
27 ComponentClass,
28 Group,
29}
30
31impl PcbZonePlacementSource {
32 pub const fn as_str(self) -> &'static str {
33 match self {
34 Self::SheetName => "sheetname",
35 Self::ComponentClass => "component_class",
36 Self::Group => "group",
37 }
38 }
39}
40
41#[derive(Clone, Debug, Eq, PartialEq)]
42pub struct PcbZonePlacement {
43 pub enabled: bool,
44 pub has_enabled: bool,
47 pub source_type: PcbZonePlacementSource,
48 pub source: String,
49}
50
51#[derive(Clone, Debug, PartialEq)]
52pub struct PcbZoneLayerProperty {
53 pub layer: String,
54 pub hatch_offset: PcbPoint,
55 pub source_range: Range<usize>,
56}
57
58#[derive(Clone, Debug, PartialEq)]
59pub struct PcbZonePolygon {
60 pub points: Vec<PcbPoint>,
63 pub polygon_points: Vec<PcbPolygonPoint>,
65 pub source_range: Range<usize>,
66}
67
68#[derive(Clone, Debug, PartialEq)]
69pub struct PcbZoneFilledPolygon {
70 pub layer: String,
71 pub island: bool,
72 pub points: Vec<PcbPoint>,
73 pub source_range: Range<usize>,
74}
75
76#[derive(Clone, Debug, PartialEq)]
77pub struct PcbZone {
78 pub net: PcbNetRef,
79 pub net_name: Option<String>,
81 pub has_explicit_net_name: bool,
82 pub layers: Vec<String>,
83 pub layers_plural: bool,
84 pub locked: bool,
85 pub uuid: Option<String>,
86 pub name: Option<String>,
87 pub hatch_style: String,
88 pub hatch_pitch: f64,
89 pub priority: i64,
90 pub connect_pads_mode: Option<String>,
91 pub connect_pads_clearance: f64,
92 pub min_thickness: f64,
93 pub filled_areas_thickness: bool,
94 pub fill_enabled: bool,
95 pub fill_mode: Option<String>,
96 pub hatch_thickness: Option<f64>,
97 pub hatch_gap: Option<f64>,
98 pub hatch_orientation: Option<f64>,
99 pub hatch_smoothing_level: Option<i64>,
103 pub hatch_smoothing_value: Option<f64>,
104 pub hatch_border_algorithm: Option<String>,
105 pub hatch_min_hole_area: Option<f64>,
106 pub thermal_gap: f64,
107 pub thermal_bridge_width: f64,
108 pub island_removal_mode: Option<i64>,
109 pub island_area_min: Option<f64>,
110 pub unmodeled_fill_settings: Vec<String>,
114 pub keepout: Option<PcbZoneKeepout>,
115 pub placement: Option<PcbZonePlacement>,
116 pub layer_properties: Vec<PcbZoneLayerProperty>,
117 pub polygons: Vec<PcbZonePolygon>,
118 pub filled_polygons: Vec<PcbZoneFilledPolygon>,
119 pub source_range: Range<usize>,
120}
121
122#[derive(Clone, Debug, PartialEq)]
125pub struct PcbFootprintZone {
126 pub footprint_index: usize,
127 pub zone: PcbZone,
128}
129
130struct ZoneCollections {
131 layer_properties: Vec<PcbZoneLayerProperty>,
132 polygons: Vec<PcbZonePolygon>,
133 filled_polygons: Vec<PcbZoneFilledPolygon>,
134}
135
136#[allow(
137 clippy::too_many_lines,
138 reason = "PCB zone decoder validates outline, fill, keepout, and hatch fields in one bounded pass"
139)]
140pub(super) fn zone_from_span(
141 source: &str,
142 span: &FormSpan,
143 limits: PcbLimits,
144) -> Result<PcbZone, Error> {
145 let children = direct_children(source, span, limits.max_object_children, limits)?;
146 let plural_layer_values = child(&children, "layers")
147 .map(|item| bounded_scalar_values(source, item, limits.max_layers))
148 .transpose()?;
149 let layers_plural = plural_layer_values
150 .as_ref()
151 .is_some_and(|values| !values.is_empty());
152 let layers = if let Some(values) = plural_layer_values.filter(|values| !values.is_empty()) {
153 values.iter().map(token_string).collect()
154 } else if let Some(layer) = optional_child_string(source, &children, "layer")? {
155 vec![layer]
156 } else {
157 Vec::new()
158 };
159
160 let net_name_span = child(&children, "net_name");
161 let net_name = net_name_span
162 .map(|item| first_string(source, item))
163 .transpose()?
164 .flatten()
165 .or_else(|| net_name_span.map(|_| String::new()));
166 let mut net = child_net_ref_or_zero(source, &children)?;
167 if let Some(explicit_name) = &net_name {
168 net.name = Some(explicit_name.clone());
169 }
170
171 let hatch = child(&children, "hatch");
172 let hatch_values = hatch
173 .map(|item| bounded_scalar_values(source, item, 2))
174 .transpose()?
175 .unwrap_or_default();
176 let mut connect_pads_mode = None;
177 let mut connect_pads_clearance = 0.5;
178 for declaration in children
179 .iter()
180 .filter(|field| field.head.as_deref() == Some("connect_pads"))
181 {
182 for value in bounded_scalar_values(source, declaration, limits.max_object_children)? {
183 if value.kind != TokenKind::Atom
184 || !matches!(value.lexeme, "yes" | "no" | "thru_hole_only")
185 {
186 return Err(source_error(
187 "Expected known connect_pads mode atom",
188 declaration.start,
189 ));
190 }
191 connect_pads_mode = Some(value.lexeme.to_owned());
192 }
193 for field in direct_children(source, declaration, limits.max_object_children, limits)? {
194 let values = bounded_scalar_values(source, &field, limits.max_object_children)?;
195 let head = Lexer::new(field.text(source)?).nth(1).transpose()?;
196 if field.head.as_deref() != Some("clearance")
197 || !head.is_some_and(|token| token.kind == TokenKind::Atom)
198 || !direct_children(source, &field, limits.max_object_children, limits)?.is_empty()
199 {
200 return Err(source_error(
201 "Expected connect_pads clearance child",
202 field.start,
203 ));
204 }
205 let [value] = values.as_slice() else {
206 return Err(source_error(
207 "Expected one connect_pads clearance number",
208 field.start,
209 ));
210 };
211 if !matches!(value.kind, TokenKind::Integer | TokenKind::Float) {
212 return Err(source_error(
213 "Expected connect_pads clearance number",
214 field.start,
215 ));
216 }
217 connect_pads_clearance = required_f64(
218 Some(value),
219 "Expected finite connect_pads clearance",
220 &field,
221 )?;
222 }
223 }
224 let fill = child(&children, "fill");
225 let fill_enabled = fill
226 .map(|item| bounded_scalar_values(source, item, 1))
227 .transpose()?
228 .and_then(|values| values.first().map(token_string))
229 .is_some_and(|value| value == "yes");
230 let fill_children = fill
231 .map(|item| direct_children(source, item, limits.max_object_children, limits))
232 .transpose()?
233 .unwrap_or_default();
234 let unmodeled_fill_settings = unmodeled_fill_settings(source, &fill_children)?;
235
236 let collections = zone_collections(source, &children, limits)?;
237
238 Ok(PcbZone {
239 net,
240 net_name,
241 has_explicit_net_name: net_name_span.is_some(),
242 layers,
243 layers_plural,
244 locked: child_bool(source, &children, "locked")?,
245 uuid: optional_uuid(source, &children)?,
246 name: optional_child_string(source, &children, "name")?.filter(|name| !name.is_empty()),
247 hatch_style: hatch_values
248 .first()
249 .map(token_string)
250 .unwrap_or_else(|| "edge".to_owned()),
251 hatch_pitch: optional_f64(hatch_values.get(1), hatch.unwrap_or(span))?.unwrap_or(0.5),
252 priority: optional_child_i64(source, &children, "priority")?.unwrap_or(0),
253 connect_pads_mode,
254 connect_pads_clearance,
255 min_thickness: optional_child_f64(source, &children, "min_thickness")?.unwrap_or(0.25),
256 filled_areas_thickness: optional_child_string(source, &children, "filled_areas_thickness")?
257 .is_some_and(|value| value == "yes"),
258 fill_enabled,
259 fill_mode: optional_child_string(source, &fill_children, "mode")?,
260 hatch_thickness: optional_child_f64(source, &fill_children, "hatch_thickness")?,
261 hatch_gap: optional_child_f64(source, &fill_children, "hatch_gap")?,
262 hatch_orientation: optional_child_f64(source, &fill_children, "hatch_orientation")?,
263 hatch_smoothing_level: optional_child_i64(source, &fill_children, "hatch_smoothing_level")?,
264 hatch_smoothing_value: optional_child_f64(source, &fill_children, "hatch_smoothing_value")?,
265 hatch_border_algorithm: optional_child_string(
266 source,
267 &fill_children,
268 "hatch_border_algorithm",
269 )?,
270 hatch_min_hole_area: optional_child_f64(source, &fill_children, "hatch_min_hole_area")?,
271 thermal_gap: optional_child_f64(source, &fill_children, "thermal_gap")?.unwrap_or(0.5),
272 thermal_bridge_width: optional_child_f64(source, &fill_children, "thermal_bridge_width")?
273 .unwrap_or(0.5),
274 island_removal_mode: optional_child_i64(source, &fill_children, "island_removal_mode")?,
275 island_area_min: optional_child_f64(source, &fill_children, "island_area_min")?,
276 unmodeled_fill_settings,
277 keepout: keepout_from_children(source, &children, limits)?,
278 placement: placement_from_children(source, &children, limits)?,
279 layer_properties: collections.layer_properties,
280 polygons: collections.polygons,
281 filled_polygons: collections.filled_polygons,
282 source_range: span.range.clone(),
283 })
284}
285
286fn unmodeled_fill_settings(source: &str, children: &[FormSpan]) -> Result<Vec<String>, Error> {
287 let mut result = Vec::new();
288 for child in children {
289 let Some(head) = child.head.as_deref() else {
290 continue;
291 };
292 match head {
293 "thermal_gap"
294 | "thermal_bridge_width"
295 | "island_removal_mode"
296 | "island_area_min"
297 | "hatch_thickness"
298 | "hatch_gap"
299 | "hatch_orientation"
300 | "hatch_smoothing_level"
301 | "hatch_smoothing_value"
302 | "hatch_border_algorithm"
303 | "hatch_min_hole_area" => {}
304 "mode" => {
305 let mode = first_string(source, child)?.unwrap_or_default();
308 if !matches!(mode.as_str(), "polygon" | "hatch" | "segment") {
309 result.push(format!("mode={mode}"));
310 }
311 }
312 _ => result.push(head.to_owned()),
313 }
314 }
315 Ok(result)
316}
317
318fn zone_collections(
319 source: &str,
320 children: &[FormSpan],
321 limits: PcbLimits,
322) -> Result<ZoneCollections, Error> {
323 let mut result = ZoneCollections {
324 layer_properties: Vec::new(),
325 polygons: Vec::new(),
326 filled_polygons: Vec::new(),
327 };
328 let mut point_count = 0usize;
329 for item in children {
330 match item.head.as_deref() {
331 Some("property") => {
332 if let Some(property) = layer_property_from_span(source, item, limits)? {
333 bounded_push(
334 &mut result.layer_properties,
335 property,
336 limits.max_zone_layer_properties,
337 )?;
338 }
339 }
340 Some("polygon") => {
341 ensure_polygon_capacity(&result, limits)?;
342 let (points, polygon_points) =
343 polygon_points(source, item, limits, &mut point_count)?;
344 result.polygons.push(PcbZonePolygon {
345 points,
346 polygon_points,
347 source_range: item.range.clone(),
348 });
349 }
350 Some("filled_polygon") => {
351 ensure_polygon_capacity(&result, limits)?;
352 let item_children =
353 direct_children(source, item, limits.max_object_children, limits)?;
354 result.filled_polygons.push(PcbZoneFilledPolygon {
355 layer: optional_child_string(source, &item_children, "layer")?
356 .unwrap_or_default(),
357 island: filled_island(source, &item_children, limits)?,
358 points: polygon_points_from_children(
359 source,
360 &item_children,
361 limits,
362 &mut point_count,
363 )?
364 .0,
365 source_range: item.range.clone(),
366 });
367 }
368 _ => {}
369 }
370 }
371 Ok(result)
372}
373
374fn ensure_polygon_capacity(result: &ZoneCollections, limits: PcbLimits) -> Result<(), Error> {
375 if result
376 .polygons
377 .len()
378 .saturating_add(result.filled_polygons.len())
379 >= limits.max_zone_polygons
380 {
381 Err(Error::at(
382 ErrorPhase::Tree,
383 ErrorKind::ResourceLimit,
384 "PCB zone polygons exceed max_zone_polygons",
385 Position::START,
386 ))
387 } else {
388 Ok(())
389 }
390}
391
392fn filled_island(source: &str, children: &[FormSpan], limits: PcbLimits) -> Result<bool, Error> {
393 let rows = children
394 .iter()
395 .filter(|row| row.head.as_deref() == Some("island"))
396 .collect::<Vec<_>>();
397 let Some(row) = rows.first() else {
398 return Ok(false);
399 };
400 if rows.len() != 1
401 || !direct_children(source, row, limits.max_object_children, limits)?.is_empty()
402 {
403 return Err(source_error(
404 "Repeated or nested island forms are unqualified",
405 row.start,
406 ));
407 }
408 let head = Lexer::new(row.text(source)?).nth(1).transpose()?;
409 if !head.is_some_and(|token| token.kind == TokenKind::Atom) {
410 return Err(source_error("Expected island atom", row.start));
411 }
412 match bounded_scalar_values(source, row, limits.max_object_children)?.as_slice() {
413 [] => Ok(true),
414 [value] if value.kind == TokenKind::Atom => match value.lexeme {
415 "yes" | "true" => Ok(true),
416 "no" | "false" => Ok(false),
417 _ => Err(source_error(
418 "Expected island yes/no/true/false atom",
419 row.start,
420 )),
421 },
422 _ => Err(source_error(
423 "Expected one island boolean atom or bare form",
424 row.start,
425 )),
426 }
427}
428
429fn keepout_from_children(
430 source: &str,
431 children: &[FormSpan],
432 limits: PcbLimits,
433) -> Result<Option<PcbZoneKeepout>, Error> {
434 let declarations = children
435 .iter()
436 .filter(|field| field.head.as_deref() == Some("keepout"))
437 .collect::<Vec<_>>();
438 if declarations.is_empty() {
439 return Ok(None);
440 }
441 let mut result = PcbZoneKeepout {
442 tracks: "not_allowed".into(),
443 vias: "not_allowed".into(),
444 pads: "allowed".into(),
445 copperpour: "not_allowed".into(),
446 footprints: "allowed".into(),
447 has_tracks: false,
448 has_vias: false,
449 has_pads: false,
450 has_copperpour: false,
451 has_footprints: false,
452 };
453 for declaration in declarations {
456 if !scalar_values(source, declaration)?.is_empty() {
457 return Err(source_error(
458 "Expected keepout restriction child",
459 declaration.start,
460 ));
461 }
462 result.pads = "allowed".into();
463 result.footprints = "allowed".into();
464 result.has_pads = false;
465 result.has_footprints = false;
466 for field in direct_children(source, declaration, limits.max_object_children, limits)? {
467 let atoms = bounded_scalar_values(source, &field, limits.max_object_children)?;
468 let head = Lexer::new(field.text(source)?).nth(1).transpose()?;
469 if !head.is_some_and(|token| token.kind == TokenKind::Atom)
470 || !direct_children(source, &field, limits.max_object_children, limits)?.is_empty()
471 {
472 return Err(source_error(
473 "Expected keepout restriction atom",
474 field.start,
475 ));
476 }
477 let [value] = atoms.as_slice() else {
478 return Err(source_error(
479 "Expected one keepout allowed/not_allowed atom",
480 field.start,
481 ));
482 };
483 if value.kind != TokenKind::Atom || !matches!(value.lexeme, "allowed" | "not_allowed") {
484 return Err(source_error(
485 "Expected keepout allowed/not_allowed atom",
486 field.start,
487 ));
488 }
489 let (target, present) = match field.head.as_deref() {
490 Some("tracks") => (&mut result.tracks, &mut result.has_tracks),
491 Some("vias") => (&mut result.vias, &mut result.has_vias),
492 Some("pads") => (&mut result.pads, &mut result.has_pads),
493 Some("copperpour") => (&mut result.copperpour, &mut result.has_copperpour),
494 Some("footprints") => (&mut result.footprints, &mut result.has_footprints),
495 _ => return Err(source_error("Unknown keepout restriction", field.start)),
496 };
497 *target = value.lexeme.to_owned();
498 *present = true;
499 }
500 }
501 Ok(Some(result))
502}
503
504fn placement_from_children(
505 source: &str,
506 children: &[FormSpan],
507 limits: PcbLimits,
508) -> Result<Option<PcbZonePlacement>, Error> {
509 let mut placements = children
510 .iter()
511 .filter(|field| field.head.as_deref() == Some("placement"));
512 let Some(placement) = placements.next() else {
513 return Ok(None);
514 };
515 if placements.next().is_some() {
516 return Err(source_error(
517 "Repeated placement stanzas require ordered interpretation",
518 placement.start,
519 ));
520 }
521 if !scalar_values(source, placement)?.is_empty() {
522 return Err(source_error("Expected placement child", placement.start));
523 }
524 let values = direct_children(source, placement, limits.max_object_children, limits)?;
525 let mut source_type = PcbZonePlacementSource::SheetName;
526 let mut source_value = String::new();
527 let mut has_enabled = false;
528 let mut enabled_value = false;
529 for field in values {
530 let atoms = bounded_scalar_values(source, &field, limits.max_object_children)?;
531 let head = Lexer::new(field.text(source)?).nth(1).transpose()?;
532 if !head.is_some_and(|token| token.kind == TokenKind::Atom)
533 || !direct_children(source, &field, limits.max_object_children, limits)?.is_empty()
534 {
535 return Err(source_error("Expected placement scalar child", field.start));
536 }
537 let [value] = atoms.as_slice() else {
538 return Err(source_error("Expected one placement value", field.start));
539 };
540 match field.head.as_deref() {
541 Some("enabled") => {
542 if value.kind != TokenKind::Atom {
543 return Err(source_error("Expected enabled yes/no atom", field.start));
544 }
545 enabled_value = match value.lexeme {
546 "yes" => true,
547 "no" => false,
548 _ => return Err(source_error("Expected enabled yes/no atom", field.start)),
549 };
550 has_enabled = true;
551 }
552 Some("sheetname" | "component_class" | "group") => {
553 if !matches!(value.kind, TokenKind::QuotedString | TokenKind::Atom) {
554 return Err(source_error(
555 "Expected placement selector string",
556 field.start,
557 ));
558 }
559 source_type = match field.head.as_deref() {
560 Some("sheetname") => PcbZonePlacementSource::SheetName,
561 Some("component_class") => PcbZonePlacementSource::ComponentClass,
562 _ => PcbZonePlacementSource::Group,
563 };
564 source_value = token_string(value);
565 }
566 _ => return Err(source_error("Unknown placement child", field.start)),
567 }
568 }
569 Ok(Some(PcbZonePlacement {
570 enabled: enabled_value,
571 has_enabled,
572 source_type,
573 source: source_value,
574 }))
575}
576
577fn layer_property_from_span(
578 source: &str,
579 property: &FormSpan,
580 limits: PcbLimits,
581) -> Result<Option<PcbZoneLayerProperty>, Error> {
582 let children = direct_children(source, property, limits.max_object_children, limits)?;
583 let Some(hatch) = child(&children, "hatch_position") else {
584 return Ok(None);
585 };
586 let hatch_children = direct_children(source, hatch, limits.max_object_children, limits)?;
587 let Some(xy) = child(&hatch_children, "xy") else {
588 return Ok(None);
589 };
590 let values = bounded_scalar_values(source, xy, 2)?;
591 if values.len() < 2 {
592 return Ok(None);
593 }
594 Ok(Some(PcbZoneLayerProperty {
595 layer: optional_child_string(source, &children, "layer")?.unwrap_or_default(),
596 hatch_offset: PcbPoint {
597 x: required_f64(values.first(), "Expected zone hatch x", xy)?,
598 y: required_f64(values.get(1), "Expected zone hatch y", xy)?,
599 },
600 source_range: property.range.clone(),
601 }))
602}
603
604fn polygon_points(
605 source: &str,
606 polygon: &FormSpan,
607 limits: PcbLimits,
608 total: &mut usize,
609) -> Result<(Vec<PcbPoint>, Vec<PcbPolygonPoint>), Error> {
610 let children = direct_children(source, polygon, limits.max_object_children, limits)?;
611 polygon_points_from_children(source, &children, limits, total)
612}
613
614fn polygon_points_from_children(
617 source: &str,
618 children: &[FormSpan],
619 limits: PcbLimits,
620 total: &mut usize,
621) -> Result<(Vec<PcbPoint>, Vec<PcbPolygonPoint>), Error> {
622 let Some(points) = child(children, "pts") else {
623 return Ok((Vec::new(), Vec::new()));
624 };
625 let remaining = limits.max_zone_points.saturating_sub(*total);
626 let point_spans = direct_children(source, points, remaining, limits).map_err(|error| {
627 if error.kind == ErrorKind::ResourceLimit {
628 Error::at(
629 ErrorPhase::Tree,
630 ErrorKind::ResourceLimit,
631 "PCB zone points exceed max_zone_points",
632 error.position.unwrap_or(Position::START),
633 )
634 } else {
635 error
636 }
637 })?;
638 let mut decoded = Vec::with_capacity(point_spans.len());
639 let mut elements = Vec::with_capacity(point_spans.len());
640 for point in point_spans {
641 match point.head.as_deref() {
642 Some("xy") => {
643 let values = bounded_scalar_values(source, &point, 2)?;
644 let xy = PcbPoint {
645 x: required_f64(values.first(), "Expected zone point x", &point)?,
646 y: required_f64(values.get(1), "Expected zone point y", &point)?,
647 };
648 decoded.push(xy);
649 elements.push(PcbPolygonPoint::Xy(xy));
650 }
651 Some("arc") => {
652 let fields = direct_children(source, &point, limits.max_object_children, limits)?;
653 let start = required_point(source, &fields, "start", &point)?;
654 let mid = required_point(source, &fields, "mid", &point)?;
655 let end = required_point(source, &fields, "end", &point)?;
656 decoded.extend([start, mid, end]);
657 elements.push(PcbPolygonPoint::Arc { start, mid, end });
658 }
659 _ => {
660 return Err(source_error(
661 "Expected zone polygon xy or arc element",
662 point.start,
663 ));
664 }
665 }
666 }
667 *total += decoded.len();
668 if *total > limits.max_zone_points {
669 return Err(Error::at(
670 ErrorPhase::Tree,
671 ErrorKind::ResourceLimit,
672 "PCB zone points exceed max_zone_points",
673 points.start,
674 ));
675 }
676 Ok((decoded, elements))
677}