1#[cfg(feature = "embedded-resource-zstd")]
4use crate::embedded_resource::decoded_data;
5use crate::embedded_resource::{EmbeddedFile, EmbeddedFileOwner, encoded_data, metadata_from_span};
6use crate::pcb::{
7 PcbFootprint, PcbGraphic, PcbLimits, PcbModelReference, PcbPad, PcbZone,
8 StandaloneFootprintCounts, standalone_footprint_from_span, standalone_graphic_from_span,
9 standalone_model_from_span, standalone_pad_from_span, standalone_zone_from_span,
10};
11use crate::sexpr::{
12 Error, ErrorKind, ErrorPhase, Lexer, Patch, Position, Sexp, Token, TokenKind,
13 apply_patches_with_limit, build_with_limit, decode_quoted,
14};
15use crate::sexpr_projection::scan_form_spans;
16use crate::sexpr_projection::{FormSpan, Selector};
17use std::borrow::Cow;
18use std::collections::BTreeSet;
19use std::io::{Read, Write};
20use std::ops::Range;
21
22#[derive(Clone, Copy, Debug, Eq, PartialEq)]
25pub struct FootprintLimits {
26 pub max_source_bytes: usize,
27 pub max_output_bytes: usize,
28 pub max_depth: usize,
29 pub max_properties: usize,
30 pub max_pads: usize,
31 pub max_models: usize,
32 pub max_graphics: usize,
33 pub max_texts: usize,
34 pub max_text_boxes: usize,
35 pub max_text_carriers: usize,
36 pub max_object_nodes: usize,
37 pub max_embedded_files: usize,
38}
39
40impl Default for FootprintLimits {
41 fn default() -> Self {
42 Self {
43 max_source_bytes: usize::MAX,
44 max_output_bytes: usize::MAX,
45 max_depth: usize::MAX,
46 max_properties: usize::MAX,
47 max_pads: usize::MAX,
48 max_models: usize::MAX,
49 max_graphics: usize::MAX,
50 max_texts: usize::MAX,
51 max_text_boxes: usize::MAX,
52 max_text_carriers: usize::MAX,
53 max_object_nodes: usize::MAX,
54 max_embedded_files: usize::MAX,
55 }
56 }
57}
58
59pub fn source_footprint_name(source: &str) -> Result<Cow<'_, str>, Error> {
65 let (_, token) = source_footprint_header(source)?;
66 Ok(decoded(token))
67}
68
69pub fn rename_source_footprint_name(
72 source: &str,
73 new_stored_name: &str,
74 max_output_bytes: usize,
75) -> Result<FootprintEdit, Error> {
76 let (root, token) = source_footprint_header(source)?;
77 if new_stored_name.is_empty() || new_stored_name.contains('\0') {
78 return Err(source_error(
79 "Expected a nonempty footprint name without NUL",
80 root.start,
81 ));
82 }
83 if decoded(token.clone()) == new_stored_name {
84 if source.len() > max_output_bytes {
85 return Err(Error::build(
86 ErrorKind::ResourceLimit,
87 "Renamed source exceeds max_output_bytes",
88 ));
89 }
90 return Ok(FootprintEdit {
91 source: source.to_owned(),
92 changed: false,
93 });
94 }
95 let replacement =
96 build_with_limit(&Sexp::Quoted(new_stored_name.to_owned()), max_output_bytes)?;
97 let start_offset = root.range.start + token.position.offset;
98 Ok(FootprintEdit {
99 source: apply_patches_with_limit(
100 source,
101 &[Patch::new(
102 start_offset,
103 start_offset + token.lexeme.len(),
104 replacement,
105 )],
106 max_output_bytes,
107 )?,
108 changed: true,
109 })
110}
111
112fn source_footprint_header(source: &str) -> Result<(FormSpan, Token<'_>), Error> {
113 let roots = scan_form_spans(
114 source,
115 &Selector {
116 min_depth: Some(0),
117 max_depth: Some(0),
118 ..Selector::default()
119 },
120 )?;
121 let [root]: [FormSpan; 1] = roots.try_into().map_err(|_| {
122 source_error(
123 "Expected exactly one top-level footprint or module form",
124 Position::START,
125 )
126 })?;
127 let text = root.text(source)?;
128 let token = (|| {
129 let mut lexer = Lexer::new(text);
130 expect_kind(
131 lexer.next(),
132 TokenKind::Left,
133 "Expected footprint opening parenthesis",
134 )?;
135 let head = next_value(lexer.next(), "Expected footprint or module root")?;
136 if head.kind != TokenKind::Atom || !matches!(head.lexeme, "footprint" | "module") {
137 return Err(source_error(
138 "Expected footprint or module root",
139 head.position,
140 ));
141 }
142 next_value(lexer.next(), "Expected footprint name")
143 })()
144 .map_err(|error| rebase_error(error, &root))?;
145 Ok((root, token))
146}
147
148#[derive(Clone, Debug, Eq, PartialEq)]
150pub struct FootprintProperty<'a> {
151 pub name: Cow<'a, str>,
152 pub value: Cow<'a, str>,
153 value_range: Range<usize>,
154}
155
156#[derive(Clone, Debug)]
158pub struct FootprintView<'a> {
159 pub(crate) source: &'a str,
160 pub(crate) root: FormSpan,
161 pub(crate) properties: Vec<FormSpan>,
162 pub(crate) texts: Vec<FormSpan>,
163 pub(crate) text_boxes: Vec<FormSpan>,
164 pads: Vec<FormSpan>,
165 models: Vec<FormSpan>,
166 graphics: Vec<FormSpan>,
167 zones: Vec<FormSpan>,
168 embedded_files: Vec<FormSpan>,
169 pad_count: usize,
170 pub(crate) limits: FootprintLimits,
171}
172
173#[derive(Clone, Debug)]
175pub struct FootprintDocument {
176 source: String,
177 limits: FootprintLimits,
178}
179
180impl FootprintDocument {
181 pub fn parse(source: String, limits: FootprintLimits) -> Result<Self, Error> {
183 FootprintView::parse(&source, limits)?;
184 Ok(Self { source, limits })
185 }
186
187 pub fn from_reader(mut reader: impl Read, limits: FootprintLimits) -> Result<Self, Error> {
189 let read_limit = limits.max_source_bytes.saturating_add(1);
191 let mut bytes = Vec::new();
192 reader
193 .by_ref()
194 .take(read_limit as u64)
195 .read_to_end(&mut bytes)
196 .map_err(footprint_io_error)?;
197 if bytes.len() > limits.max_source_bytes {
198 return Err(limit_error());
199 }
200 let source = crate::sexpr::utf8_text(&bytes)?.to_owned();
201 Self::parse(source, limits)
202 }
203
204 pub fn source(&self) -> &str {
205 &self.source
206 }
207
208 pub fn into_source(self) -> String {
209 self.source
210 }
211
212 pub fn limits(&self) -> FootprintLimits {
213 self.limits
214 }
215
216 pub fn view(&self) -> Result<FootprintView<'_>, Error> {
217 FootprintView::parse(&self.source, self.limits)
218 }
219
220 pub fn write_to(&self, mut writer: impl Write) -> Result<(), Error> {
222 if self.source.len() > self.limits.max_output_bytes {
223 return Err(Error::build(
224 ErrorKind::ResourceLimit,
225 "Footprint output exceeds max_output_bytes",
226 ));
227 }
228 writer
229 .write_all(self.source.as_bytes())
230 .map_err(footprint_io_error)
231 }
232}
233
234struct FootprintChildren {
235 properties: Vec<FormSpan>,
236 texts: Vec<FormSpan>,
237 text_boxes: Vec<FormSpan>,
238 pads: Vec<FormSpan>,
239 models: Vec<FormSpan>,
240 graphics: Vec<FormSpan>,
241 zones: Vec<FormSpan>,
242 embedded_files: Vec<FormSpan>,
243 pad_count: usize,
244}
245
246impl<'a> FootprintView<'a> {
247 pub fn parse(source: &'a str, limits: FootprintLimits) -> Result<Self, Error> {
249 let root_selector = Selector {
250 min_depth: Some(0),
251 max_depth: Some(0),
252 ..Selector::default()
253 };
254 let roots = scan_form_spans(source, &root_selector)?;
255 let [root] = roots.try_into().map_err(|_| {
256 source_error(
257 "Expected exactly one top-level footprint form",
258 Position::START,
259 )
260 })?;
261 if root.head.as_deref() != Some("footprint") {
262 return Err(source_error("Expected a footprint root", root.start));
263 }
264
265 let child_selector = Selector {
266 paths: Some(BTreeSet::from([
267 vec!["footprint".to_owned(), "property".to_owned()],
268 vec!["footprint".to_owned(), "pad".to_owned()],
269 vec!["footprint".to_owned(), "fp_text".to_owned()],
270 vec!["footprint".to_owned(), "fp_text_box".to_owned()],
271 vec!["footprint".to_owned(), "model".to_owned()],
272 vec!["footprint".to_owned(), "fp_line".to_owned()],
273 vec!["footprint".to_owned(), "fp_rect".to_owned()],
274 vec!["footprint".to_owned(), "fp_arc".to_owned()],
275 vec!["footprint".to_owned(), "fp_circle".to_owned()],
276 vec!["footprint".to_owned(), "fp_poly".to_owned()],
277 vec!["footprint".to_owned(), "fp_curve".to_owned()],
278 vec!["footprint".to_owned(), "zone".to_owned()],
279 vec![
280 "footprint".to_owned(),
281 "embedded_files".to_owned(),
282 "file".to_owned(),
283 ],
284 ])),
285 min_depth: Some(1),
286 max_depth: Some(2),
287 ..Selector::default()
288 };
289 let spans = scan_form_spans(source, &child_selector)?;
290 let children = partition_children(spans, limits)?;
291 Ok(Self {
292 source,
293 root,
294 properties: children.properties,
295 texts: children.texts,
296 text_boxes: children.text_boxes,
297 pads: children.pads,
298 models: children.models,
299 graphics: children.graphics,
300 zones: children.zones,
301 embedded_files: children.embedded_files,
302 pad_count: children.pad_count,
303 limits,
304 })
305 }
306
307 pub fn name(&self) -> Result<Cow<'a, str>, Error> {
309 let text = self.root.text(self.source)?;
310 (|| {
311 let mut lexer = Lexer::new(text);
312 expect_kind(
313 lexer.next(),
314 TokenKind::Left,
315 "Expected footprint opening parenthesis",
316 )?;
317 expect_atom(lexer.next(), "footprint", "Expected footprint root")?;
318 let token = next_value(lexer.next(), "Expected footprint name")?;
319 Ok(decoded(token))
320 })()
321 .map_err(|error| rebase_error(error, &self.root))
322 }
323
324 pub fn pad_count(&self) -> usize {
325 self.pad_count
326 }
327
328 pub fn metadata(&self) -> Result<PcbFootprint, Error> {
331 standalone_footprint_from_span(
332 self.source,
333 &self.root,
334 self.pcb_limits(),
335 StandaloneFootprintCounts {
336 properties: self.properties.len(),
337 graphics: self.graphics.len(),
338 texts: self.texts.len(),
339 text_boxes: self.text_boxes.len(),
340 pads: self.pads.len(),
341 models: self.models.len(),
342 embedded_files: self.embedded_files.len(),
343 },
344 )
345 }
346
347 pub fn pads(&self) -> impl Iterator<Item = Result<PcbPad, Error>> + '_ {
350 let limits = self.pcb_limits();
351 self.pads
352 .iter()
353 .map(move |span| standalone_pad_from_span(self.source, span, limits))
354 }
355
356 pub fn models(&self) -> impl Iterator<Item = Result<PcbModelReference, Error>> + '_ {
358 let limits = self.pcb_limits();
359 self.models
360 .iter()
361 .map(move |span| standalone_model_from_span(self.source, span, limits))
362 }
363
364 pub fn graphics(&self) -> impl Iterator<Item = Result<PcbGraphic, Error>> + '_ {
366 let limits = self.pcb_limits();
367 self.graphics
368 .iter()
369 .map(move |span| standalone_graphic_from_span(self.source, span, limits))
370 }
371
372 pub fn zones(&self) -> impl Iterator<Item = Result<PcbZone, Error>> + '_ {
375 let limits = self.pcb_limits();
376 self.zones
377 .iter()
378 .map(move |span| standalone_zone_from_span(self.source, span, limits))
379 }
380
381 pub fn embedded_files(&self) -> impl Iterator<Item = Result<EmbeddedFile, Error>> + '_ {
383 self.embedded_files.iter().map(|span| {
384 metadata_from_span(self.source, span, EmbeddedFileOwner::StandaloneFootprint)
385 })
386 }
387
388 pub fn embedded_file_encoded_data(
390 &self,
391 file: &EmbeddedFile,
392 maximum: usize,
393 ) -> Result<Option<String>, Error> {
394 if file.owner != EmbeddedFileOwner::StandaloneFootprint
395 || !self
396 .embedded_files
397 .iter()
398 .any(|span| span.range == file.source_range)
399 {
400 return Err(Error::build(
401 ErrorKind::InvalidSpan,
402 format!(
403 "Embedded resource {:?} does not belong to this footprint view",
404 file.name
405 ),
406 ));
407 }
408 encoded_data(self.source, file, maximum)
409 }
410
411 #[cfg(feature = "embedded-resource-zstd")]
413 pub fn decode_embedded_file(&self, file: &EmbeddedFile) -> Result<Option<Vec<u8>>, Error> {
414 if file.owner != EmbeddedFileOwner::StandaloneFootprint
415 || !self
416 .embedded_files
417 .iter()
418 .any(|span| span.range == file.source_range)
419 {
420 return Err(Error::build(
421 ErrorKind::InvalidSpan,
422 format!(
423 "Embedded resource {:?} does not belong to this footprint view",
424 file.name
425 ),
426 ));
427 }
428 decoded_data(self.source, file)
429 }
430
431 pub fn properties(&self) -> impl Iterator<Item = Result<FootprintProperty<'a>, Error>> + '_ {
433 self.properties
434 .iter()
435 .map(|span| property_from_span(self.source, span))
436 }
437
438 pub fn set_property(
440 &self,
441 name: &str,
442 value: &str,
443 max_output_bytes: usize,
444 ) -> Result<FootprintEdit, Error> {
445 if self.source.len() > max_output_bytes {
446 return Err(Error::build(
447 ErrorKind::ResourceLimit,
448 "Footprint output exceeds max_output_bytes",
449 ));
450 }
451 let mut matching = self.properties().filter_map(|property| match property {
452 Ok(property) if property.name == name => Some(Ok(property)),
453 Ok(_) => None,
454 Err(error) => Some(Err(error)),
455 });
456 let property = matching
457 .next()
458 .transpose()?
459 .ok_or_else(|| source_error("Footprint property was not found", self.root.start))?;
460 if matching.next().transpose()?.is_some() {
461 return Err(source_error(
462 "Footprint property name is ambiguous",
463 self.root.start,
464 ));
465 }
466 if property.value == value {
467 return Ok(FootprintEdit {
468 source: self.source.to_owned(),
469 changed: false,
470 });
471 }
472 let replacement = build_with_limit(&Sexp::Quoted(value.to_owned()), max_output_bytes)?;
473 let source = apply_patches_with_limit(
474 self.source,
475 &[Patch::new(
476 property.value_range.start,
477 property.value_range.end,
478 replacement,
479 )],
480 max_output_bytes,
481 )?;
482 Ok(FootprintEdit {
483 source,
484 changed: true,
485 })
486 }
487
488 pub(crate) fn pcb_limits(&self) -> PcbLimits {
489 let mut limits = PcbLimits::default();
490 limits.max_source_bytes = self.limits.max_source_bytes;
491 limits.max_output_bytes = self.limits.max_output_bytes;
492 limits.max_depth = self.limits.max_depth;
493 limits.max_properties = self.limits.max_properties;
494 limits.max_pads = self.limits.max_pads;
495 limits.max_models = self.limits.max_models;
496 limits.max_graphics = self.limits.max_graphics;
497 limits.max_footprint_graphics = self.limits.max_graphics;
498 limits.max_embedded_files = self.limits.max_embedded_files;
499 limits.max_object_children = self.limits.max_object_nodes;
500 limits.max_footprint_children = self.limits.max_object_nodes;
501 limits.max_footprint_header_scalars = self.limits.max_object_nodes;
502 limits.max_layers = limits.max_layers.min(self.limits.max_object_nodes);
503 limits.max_footprint_attributes = limits
504 .max_footprint_attributes
505 .min(self.limits.max_object_nodes);
506 limits.max_text_effect_children = limits
507 .max_text_effect_children
508 .min(self.limits.max_object_nodes);
509 limits.max_text_font_children = limits
510 .max_text_font_children
511 .min(self.limits.max_object_nodes);
512 limits.max_text_justify_tokens = limits
513 .max_text_justify_tokens
514 .min(self.limits.max_object_nodes);
515 limits.max_text_box_points = limits.max_text_box_points.min(self.limits.max_object_nodes);
516 limits.max_pad_header_scalars = limits
517 .max_pad_header_scalars
518 .min(self.limits.max_object_nodes);
519 limits.max_pad_children = limits.max_pad_children.min(self.limits.max_object_nodes);
520 limits.max_pad_chamfer_corners = limits
521 .max_pad_chamfer_corners
522 .min(self.limits.max_object_nodes);
523 limits.max_pad_custom_primitives = limits
524 .max_pad_custom_primitives
525 .min(self.limits.max_object_nodes);
526 limits.max_pad_custom_point_forms = limits
527 .max_pad_custom_point_forms
528 .min(self.limits.max_object_nodes);
529 limits.max_pad_custom_points = limits
530 .max_pad_custom_points
531 .min(self.limits.max_object_nodes);
532 limits.max_model_children = limits.max_model_children.min(self.limits.max_object_nodes);
533 limits.max_graphic_points = limits.max_graphic_points.min(self.limits.max_object_nodes);
534 limits.max_manufacturing_children = limits
535 .max_manufacturing_children
536 .min(self.limits.max_object_nodes);
537 limits.max_teardrop_scalars = limits
538 .max_teardrop_scalars
539 .min(self.limits.max_object_nodes);
540 limits.max_zone_layer_connections = limits
541 .max_zone_layer_connections
542 .min(self.limits.max_object_nodes);
543 limits
544 }
545}
546
547fn partition_children(
548 spans: Vec<FormSpan>,
549 limits: FootprintLimits,
550) -> Result<FootprintChildren, Error> {
551 let mut children = FootprintChildren {
552 properties: Vec::new(),
553 texts: Vec::new(),
554 text_boxes: Vec::new(),
555 pads: Vec::new(),
556 models: Vec::new(),
557 graphics: Vec::new(),
558 zones: Vec::new(),
559 embedded_files: Vec::new(),
560 pad_count: 0,
561 };
562 for span in spans {
563 match (span.depth, span.head.as_deref()) {
564 (1, Some("property")) => children.properties.push(span),
565 (1, Some("pad")) => {
566 children.pad_count = children.pad_count.saturating_add(1);
567 children.pads.push(span);
568 }
569 (1, Some("fp_text")) => children.texts.push(span),
570 (1, Some("fp_text_box")) => children.text_boxes.push(span),
571 (1, Some("model")) => children.models.push(span),
572 (1, Some("fp_line" | "fp_rect" | "fp_arc" | "fp_circle" | "fp_poly" | "fp_curve")) => {
573 children.graphics.push(span);
574 }
575 (1, Some("zone")) => children.zones.push(span),
576 (2, Some("file")) if span.path == ["footprint", "embedded_files", "file"] => {
577 children.embedded_files.push(span);
578 }
579 _ => {}
580 }
581 }
582 validate_child_limits(&children, limits)?;
583 Ok(children)
584}
585
586fn validate_child_limits(
587 children: &FootprintChildren,
588 limits: FootprintLimits,
589) -> Result<(), Error> {
590 let carrier_count = children.properties.len().saturating_add(
591 children
592 .texts
593 .len()
594 .saturating_add(children.text_boxes.len()),
595 );
596 if children.properties.len() > limits.max_properties
597 || children.pad_count > limits.max_pads
598 || children.texts.len() > limits.max_texts
599 || children.text_boxes.len() > limits.max_text_boxes
600 || carrier_count > limits.max_text_carriers
601 || children.embedded_files.len() > limits.max_embedded_files
602 || children.models.len() > limits.max_models
603 || children.graphics.len() > limits.max_graphics
604 {
605 return Err(limit_error());
606 }
607 Ok(())
608}
609
610#[derive(Clone, Debug, Eq, PartialEq)]
611pub struct FootprintEdit {
612 pub source: String,
613 pub changed: bool,
614}
615
616fn property_from_span<'a>(
617 source: &'a str,
618 span: &FormSpan,
619) -> Result<FootprintProperty<'a>, Error> {
620 let text = span.text(source)?;
621 (|| {
622 let mut lexer = Lexer::new(text);
623 expect_kind(
624 lexer.next(),
625 TokenKind::Left,
626 "Expected property opening parenthesis",
627 )?;
628 expect_atom(lexer.next(), "property", "Expected property form")?;
629 let name = next_value(lexer.next(), "Expected property name")?;
630 let value = next_value(lexer.next(), "Expected property value")?;
631 Ok(FootprintProperty {
632 name: decoded(name),
633 value: decoded(value.clone()),
634 value_range: (span.range.start + value.position.offset)
635 ..(span.range.start + value.position.offset + value.lexeme.len()),
636 })
637 })()
638 .map_err(|error| rebase_error(error, span))
639}
640
641pub(crate) fn rebase_error(mut error: Error, span: &FormSpan) -> Error {
642 if let Some(position) = error.position {
643 error.position = Some(Position {
644 offset: span.range.start.saturating_add(position.offset),
645 line: span
646 .start
647 .line
648 .saturating_add(position.line.saturating_sub(1)),
649 column: if position.line == 1 {
650 span.start
651 .column
652 .saturating_add(position.column.saturating_sub(1))
653 } else {
654 position.column
655 },
656 });
657 }
658 error
659}
660
661fn decoded(token: Token<'_>) -> Cow<'_, str> {
662 if token.kind == TokenKind::QuotedString {
663 Cow::Owned(decode_quoted(token.lexeme))
664 } else {
665 Cow::Borrowed(token.lexeme)
666 }
667}
668
669fn next_value<'a>(
670 token: Option<Result<Token<'a>, Error>>,
671 message: &'static str,
672) -> Result<Token<'a>, Error> {
673 let token = token
674 .transpose()?
675 .ok_or_else(|| source_error(message, Position::START))?;
676 if matches!(token.kind, TokenKind::Left | TokenKind::Right) {
677 return Err(source_error(message, token.position));
678 }
679 Ok(token)
680}
681
682fn expect_kind(
683 token: Option<Result<Token<'_>, Error>>,
684 kind: TokenKind,
685 message: &'static str,
686) -> Result<(), Error> {
687 let token = token
688 .transpose()?
689 .ok_or_else(|| source_error(message, Position::START))?;
690 if token.kind != kind {
691 return Err(source_error(message, token.position));
692 }
693 Ok(())
694}
695
696fn expect_atom(
697 token: Option<Result<Token<'_>, Error>>,
698 atom: &str,
699 message: &'static str,
700) -> Result<(), Error> {
701 let token = token
702 .transpose()?
703 .ok_or_else(|| source_error(message, Position::START))?;
704 if token.kind != TokenKind::Atom || token.lexeme != atom {
705 return Err(source_error(message, token.position));
706 }
707 Ok(())
708}
709
710fn source_error(message: &'static str, position: Position) -> Error {
711 Error::at(
712 ErrorPhase::Tree,
713 ErrorKind::UnexpectedToken,
714 message,
715 position,
716 )
717}
718
719fn limit_error() -> Error {
720 Error::at(
721 ErrorPhase::Tree,
722 ErrorKind::ResourceLimit,
723 "Footprint typed read exceeds configured limits",
724 Position::START,
725 )
726}
727
728fn footprint_io_error(error: std::io::Error) -> Error {
729 Error::build(
730 ErrorKind::Io,
731 format!("Footprint source I/O failed: {error}"),
732 )
733}