1use crate::sexpr::{ErrorKind, Lexer, Sexp, TokenKind, decode_quoted, parse};
3use crate::sexpr_projection::{FormSpan, Selector as FormSelector, scan_form_spans};
4use crate::{
5 KiCadColor, KiCadTextEffects, SchematicDocument, SchematicNativeLoadedNumber,
6 SchematicNativeLoadedPoint, SchematicPoint, SchematicSourceForm, SchematicWireLineStyle,
7 SourceBundleError, SourceBundleErrorKind,
8};
9use std::collections::{BTreeMap, BTreeSet};
10use std::ops::Range;
11
12mod facts;
13pub use facts::*;
14mod native_pose;
15mod root_identity;
16mod rule_area;
17pub use native_pose::SchematicDocumentationNativeTextPose;
18pub use rule_area::SchematicDocumentationNativeRuleAreaOutline;
19mod image;
20pub use image::*;
21mod native_box;
22pub use native_box::*;
23mod native_order;
24pub use native_order::*;
25mod table;
26pub use table::*;
27mod table_borders;
28pub use table_borders::*;
29
30#[derive(Clone, Copy, Debug)]
31pub struct SchematicDocumentationSourceLimits {
32 pub max_source_bytes: usize,
33 pub max_scan_bytes: usize,
34 pub max_list_forms: usize,
35 pub max_tokens: usize,
36 pub max_rows: usize,
37 pub max_points: usize,
38 pub max_group_members: usize,
39 pub max_native_angle_steps: usize,
40 pub max_image_encoded_bytes: usize,
41 pub max_image_decoded_bytes: usize,
42 pub max_image_total_decoded_bytes: usize,
43 pub max_image_pixels: u64,
44 pub max_image_total_raster_bytes: u64,
45 pub max_table_cells_per_table: usize,
46 pub max_table_total_cells: usize,
47 pub max_table_dimension_values: usize,
48 pub max_table_border_segments: usize,
49}
50impl Default for SchematicDocumentationSourceLimits {
51 fn default() -> Self {
52 Self {
53 max_source_bytes: 32 * 1024 * 1024,
54 max_scan_bytes: 128 * 1024 * 1024,
55 max_list_forms: 100_000,
56 max_tokens: 2_000_000,
57 max_rows: 100_000,
58 max_points: 100_000,
59 max_group_members: 100_000,
60 max_native_angle_steps: 4096,
61 max_image_encoded_bytes: 16 * 1024 * 1024,
62 max_image_decoded_bytes: 12 * 1024 * 1024,
63 max_image_total_decoded_bytes: 24 * 1024 * 1024,
64 max_image_pixels: 64 * 1024 * 1024,
65 max_image_total_raster_bytes: 256 * 1024 * 1024,
66 max_table_cells_per_table: 10_000,
67 max_table_total_cells: 10_000,
68 max_table_dimension_values: 20_000,
69 max_table_border_segments: 25_000,
70 }
71 }
72}
73
74#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
75pub enum SchematicDocumentationKind {
76 Text,
77 TextBox,
78 Polyline,
79 Rectangle,
80 Circle,
81 Arc,
82 Bezier,
83 Image,
84 Group,
85 Table,
86 RuleArea,
87}
88impl SchematicDocumentationKind {
89 pub fn as_str(self) -> &'static str {
90 match self {
91 Self::Text => "text",
92 Self::TextBox => "text_box",
93 Self::Polyline => "polyline",
94 Self::Rectangle => "rectangle",
95 Self::Circle => "circle",
96 Self::Arc => "arc",
97 Self::Bezier => "bezier",
98 Self::Image => "image",
99 Self::Group => "group",
100 Self::Table => "table",
101 Self::RuleArea => "rule_area",
102 }
103 }
104 fn from_head(head: &str) -> Option<Self> {
105 Some(match head {
106 "text" => Self::Text,
107 "text_box" => Self::TextBox,
108 "polyline" => Self::Polyline,
109 "rectangle" => Self::Rectangle,
110 "circle" => Self::Circle,
111 "arc" => Self::Arc,
112 "bezier" => Self::Bezier,
113 "image" => Self::Image,
114 "group" => Self::Group,
115 "table" => Self::Table,
116 "rule_area" => Self::RuleArea,
117 _ => return None,
118 })
119 }
120 fn shape(self) -> bool {
121 matches!(
122 self,
123 Self::Polyline | Self::Rectangle | Self::Circle | Self::Arc | Self::Bezier
124 )
125 }
126}
127#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
128pub struct SchematicDocumentationSelector {
129 pub kind: SchematicDocumentationKind,
130 pub ordinal: usize,
131}
132
133#[derive(Clone, Debug)]
136pub struct SchematicDocumentationRecord<'a> {
137 pub selector: SchematicDocumentationSelector,
138 pub form: SchematicSourceForm<'a>,
139 pub uuid: Result<Option<String>, SourceBundleError>,
140 pub text: Result<Option<String>, SourceBundleError>,
141 pub geometry: Result<Option<SchematicDocumentationGeometry>, SourceBundleError>,
142 pub effects: Result<Option<KiCadTextEffects>, SourceBundleError>,
143 pub stroke: Result<Option<SchematicDocumentationStroke>, SourceBundleError>,
144 pub fill: Result<Option<SchematicDocumentationFill>, SourceBundleError>,
145 pub group: Result<Option<SchematicDocumentationGroup>, SourceBundleError>,
146 pub flags: Result<SchematicDocumentationFlags, SourceBundleError>,
147 pub image: Option<SchematicDocumentationImageSource<'a>>,
149 pub table: Option<SchematicDocumentationTableSource<'a>>,
151}
152#[derive(Clone, Debug)]
155pub struct SchematicDocumentationRootUuid<'a> {
156 pub original_root_ordinal: usize,
157 pub authored_head: Option<String>,
158 pub form: SchematicSourceForm<'a>,
159 pub uuid: Result<Option<String>, SourceBundleError>,
160}
161#[derive(Clone, Debug)]
162pub struct SchematicDocumentationImageSource<'a> {
163 source: &'a str,
164 path: &'a str,
165 selector: SchematicDocumentationSelector,
166 range: Range<usize>,
167}
168#[derive(Clone, Debug)]
169pub struct SchematicDocumentationTableSource<'a> {
170 source: &'a str,
171 path: &'a str,
172 selector: SchematicDocumentationSelector,
173 range: Range<usize>,
174}
175macro_rules! source_handle {
176 ($kind:ident) => {
177 impl<'a> $kind<'a> {
178 pub fn selector(&self) -> SchematicDocumentationSelector {
179 self.selector
180 }
181 pub fn source_form(&self) -> SchematicSourceForm<'a> {
182 SchematicSourceForm {
183 ordinal: self.selector.ordinal,
184 source_range: self.range.clone(),
185 source: &self.source[self.range.clone()],
186 }
187 }
188 pub fn source_path(&self) -> &'a str {
189 self.path
190 }
191 }
192 };
193}
194source_handle!(SchematicDocumentationImageSource);
195source_handle!(SchematicDocumentationTableSource);
196
197#[derive(Debug)]
198pub struct SchematicDocumentationSourceView<'a> {
199 source: &'a str,
200 path: &'a str,
201 rows: Vec<(SchematicDocumentationSelector, FormSpan)>,
202 index: BTreeMap<SchematicDocumentationSelector, usize>,
203 limits: SchematicDocumentationSourceLimits,
204}
205pub struct SchematicDocumentationReader<'v, 'a> {
206 view: &'v SchematicDocumentationSourceView<'a>,
207 budget: Budget<'a>,
208 image_version: Option<Result<u32, SourceBundleError>>,
209}
210
211impl SchematicDocument {
212 pub fn documentation_sources(
213 &self,
214 limits: SchematicDocumentationSourceLimits,
215 ) -> Result<SchematicDocumentationSourceView<'_>, SourceBundleError> {
216 let (source, path) = (self.source(), self.source_path());
217 if source.len() > limits.max_source_bytes {
218 return Err(resource(path, "documentation source byte ceiling exceeded"));
219 }
220 let mut budget = Budget::new(path, limits);
221 budget.preflight(source)?;
222 budget.scan(source.len())?;
223 let spans = scan_form_spans(
224 source,
225 &FormSelector {
226 heads: Some(BTreeSet::from(
227 [
228 "text",
229 "text_box",
230 "polyline",
231 "rectangle",
232 "circle",
233 "arc",
234 "bezier",
235 "image",
236 "group",
237 "table",
238 "rule_area",
239 ]
240 .map(str::to_owned),
241 )),
242 min_depth: Some(1),
243 max_depth: Some(1),
244 ..Default::default()
245 },
246 )
247 .map_err(|error| sexpr_error(path, error))?;
248 if spans.len() > limits.max_rows {
249 return Err(resource(path, "documentation row ceiling exceeded"));
250 }
251 let mut counts = BTreeMap::new();
252 let rows = spans
253 .into_iter()
254 .map(|span| {
255 let kind = SchematicDocumentationKind::from_head(
256 span.head.as_deref().expect("selected head"),
257 )
258 .expect("selected kind");
259 let ordinal = counts.entry(kind).or_insert(0);
260 let selector = SchematicDocumentationSelector {
261 kind,
262 ordinal: *ordinal,
263 };
264 *ordinal += 1;
265 (selector, span)
266 })
267 .collect::<Vec<_>>();
268 let index = rows
269 .iter()
270 .enumerate()
271 .map(|(index, (selector, _))| (*selector, index))
272 .collect();
273 Ok(SchematicDocumentationSourceView {
274 source,
275 path,
276 rows,
277 index,
278 limits,
279 })
280 }
281}
282impl<'a> SchematicDocumentationSourceView<'a> {
283 pub fn selectors(&self) -> impl ExactSizeIterator<Item = SchematicDocumentationSelector> + '_ {
284 self.rows.iter().map(|(selector, _)| *selector)
285 }
286 pub fn reader(&self) -> SchematicDocumentationReader<'_, 'a> {
288 SchematicDocumentationReader {
289 view: self,
290 budget: Budget::new(self.path, self.limits),
291 image_version: None,
292 }
293 }
294}
295impl<'a> SchematicDocumentationReader<'_, 'a> {
296 pub fn root_uuid_inventory(
300 &mut self,
301 ) -> Result<Vec<SchematicDocumentationRootUuid<'a>>, SourceBundleError> {
302 let count = self.budget.root_rows_before_spans(self.view.source)?;
303 let root = Fields::new(self.view.source, self.view.path, &mut self.budget)?;
304 if root.spans.len() != count {
305 return Err(failure(
306 self.view.path,
307 SourceBundleErrorKind::Contract,
308 "root UUID inventory preflight/span count invariant failed",
309 ));
310 }
311 let mut rows = Vec::new();
312 for (ordinal, span) in root.spans.iter().enumerate() {
313 self.budget.row()?;
314 let fields = Fields::new(
315 &self.view.source[span.range.clone()],
316 self.view.path,
317 &mut self.budget,
318 )?;
319 let uuid = facet(root_identity::uuid(
320 &fields,
321 span.head.as_deref(),
322 &mut self.budget,
323 ))?;
324 if matches!(&uuid, Ok(None)) {
327 continue;
328 }
329 rows.push(SchematicDocumentationRootUuid {
330 original_root_ordinal: ordinal,
331 authored_head: span.head.clone(),
332 form: SchematicSourceForm {
333 ordinal,
334 source_range: span.range.clone(),
335 source: &self.view.source[span.range.clone()],
336 },
337 uuid,
338 });
339 }
340 Ok(rows)
341 }
342
343 #[allow(
344 clippy::too_many_lines,
345 reason = "documentation record reader decodes each authored form variant explicitly"
346 )]
347 pub fn record(
348 &mut self,
349 selector: SchematicDocumentationSelector,
350 ) -> Result<Option<SchematicDocumentationRecord<'a>>, SourceBundleError> {
351 let Some(&index) = self.view.index.get(&selector) else {
352 return Ok(None);
353 };
354 self.budget.row()?;
355 let span = &self.view.rows[index].1;
356 let fields = Fields::new(
357 &self.view.source[span.range.clone()],
358 self.view.path,
359 &mut self.budget,
360 )?;
361 let kind = selector.kind;
362 let shape = (|| {
363 if kind != SchematicDocumentationKind::RuleArea {
364 return Ok(None);
365 }
366 let mut shapes = fields.spans.iter().filter(|span| {
367 span.head
368 .as_deref()
369 .and_then(SchematicDocumentationKind::from_head)
370 .is_some_and(|kind| kind.shape())
371 });
372 let Some(shape) = shapes.next() else {
373 return Err(content(fields.path, "rule area requires one known shape"));
374 };
375 if shapes.next().is_some() {
376 return Err(content(fields.path, "rule area has competing shapes"));
377 }
378 let kind =
379 SchematicDocumentationKind::from_head(shape.head.as_deref().expect("shape head"))
380 .expect("known shape");
381 Ok(Some((
382 kind,
383 Fields::new(
384 &fields.source[shape.range.clone()],
385 fields.path,
386 &mut self.budget,
387 )?,
388 )))
389 })();
390 let effective = match &shape {
391 Ok(Some((kind, fields))) => Ok((*kind, fields)),
392 Ok(None) => Ok((kind, &fields)),
393 Err(error) => Err(error.clone()),
394 };
395 let uuid = facet(
396 effective
397 .as_ref()
398 .map_err(Clone::clone)
399 .and_then(|(_, fields)| facts::scalar(fields, "uuid", &mut self.budget)),
400 )?;
401 let geometry = facet(
402 effective
403 .as_ref()
404 .map_err(Clone::clone)
405 .and_then(|(kind, fields)| facts::geometry(fields, *kind, &mut self.budget)),
406 )?;
407 let stroke = facet(
408 effective
409 .as_ref()
410 .map_err(Clone::clone)
411 .and_then(|(_, fields)| facts::stroke(fields, &mut self.budget)),
412 )?;
413 let fill = facet(
414 effective
415 .as_ref()
416 .map_err(Clone::clone)
417 .and_then(|(_, fields)| facts::fill(fields, &mut self.budget)),
418 )?;
419 let text = facet(
420 if matches!(
421 kind,
422 SchematicDocumentationKind::Text | SchematicDocumentationKind::TextBox
423 ) {
424 facts::leading(&fields, &mut self.budget).map(|text| Some(text.to_owned()))
425 } else {
426 Ok(None)
427 },
428 )?;
429 let effects = facet(facts::effects(&fields, &mut self.budget))?;
430 let group = facet(if kind == SchematicDocumentationKind::Group {
431 facts::group(&fields, &mut self.budget).map(Some)
432 } else {
433 Ok(None)
434 })?;
435 let flags = facet(facts::flags(&fields, &mut self.budget))?;
436 Ok(Some(SchematicDocumentationRecord {
437 selector,
438 form: SchematicSourceForm {
439 ordinal: selector.ordinal,
440 source_range: span.range.clone(),
441 source: &self.view.source[span.range.clone()],
442 },
443 uuid,
444 text,
445 geometry,
446 effects,
447 stroke,
448 fill,
449 group,
450 flags,
451 image: (kind == SchematicDocumentationKind::Image).then(|| {
452 SchematicDocumentationImageSource {
453 source: self.view.source,
454 path: self.view.path,
455 selector,
456 range: span.range.clone(),
457 }
458 }),
459 table: (kind == SchematicDocumentationKind::Table).then(|| {
460 SchematicDocumentationTableSource {
461 source: self.view.source,
462 path: self.view.path,
463 selector,
464 range: span.range.clone(),
465 }
466 }),
467 }))
468 }
469}
470
471struct Budget<'a> {
472 path: &'a str,
473 limits: SchematicDocumentationSourceLimits,
474 scanned: usize,
475 tokens: usize,
476 rows: usize,
477 points: usize,
478 members: usize,
479 angle_steps: usize,
480 image_decoded: usize,
481 image_raster: u64,
482 table_cells: usize,
483 table_dimensions: usize,
484 table_border_segments: usize,
485}
486impl<'a> Budget<'a> {
487 fn new(path: &'a str, limits: SchematicDocumentationSourceLimits) -> Self {
488 Self {
489 path,
490 limits,
491 scanned: 0,
492 tokens: 0,
493 rows: 0,
494 points: 0,
495 members: 0,
496 angle_steps: 0,
497 image_decoded: 0,
498 image_raster: 0,
499 table_cells: 0,
500 table_dimensions: 0,
501 table_border_segments: 0,
502 }
503 }
504 fn scan(&mut self, bytes: usize) -> Result<(), SourceBundleError> {
505 self.scanned = self
506 .scanned
507 .checked_add(bytes)
508 .ok_or_else(|| resource(self.path, "documentation scan count overflow"))?;
509 if self.scanned > self.limits.max_scan_bytes {
510 return Err(resource(
511 self.path,
512 "documentation scan byte ceiling exceeded",
513 ));
514 }
515 Ok(())
516 }
517 fn root_rows_before_spans(&mut self, source: &str) -> Result<usize, SourceBundleError> {
520 self.scan(source.len())?;
521 let (mut depth, mut count) = (0usize, 0usize);
522 for token in Lexer::new(source) {
523 let token = token.map_err(|error| sexpr_error(self.path, error))?;
524 self.tokens = self
525 .tokens
526 .checked_add(1)
527 .ok_or_else(|| resource(self.path, "documentation token count overflow"))?;
528 if self.tokens > self.limits.max_tokens {
529 return Err(resource(
530 self.path,
531 "documentation aggregate token ceiling exceeded",
532 ));
533 }
534 match token.kind {
535 TokenKind::Left => {
536 if depth == 1 {
537 count = count
538 .checked_add(1)
539 .ok_or_else(|| resource(self.path, "root UUID row count overflow"))?;
540 if self
541 .rows
542 .checked_add(count)
543 .is_none_or(|total| total > self.limits.max_rows)
544 {
545 return Err(resource(
546 self.path,
547 "root UUID aggregate row ceiling exceeded before span allocation",
548 ));
549 }
550 }
551 depth += 1;
552 }
553 TokenKind::Right => depth = depth.saturating_sub(1),
554 _ => {}
555 }
556 }
557 Ok(count)
558 }
559 fn preflight(&mut self, source: &str) -> Result<(), SourceBundleError> {
560 self.scan(source.len())?;
561 let mut forms = 0usize;
562 let (mut depth, mut head, mut rows) = (0usize, false, 0usize);
563 for token in Lexer::new(source) {
564 let token = token.map_err(|error| sexpr_error(self.path, error))?;
565 self.tokens = self
566 .tokens
567 .checked_add(1)
568 .ok_or_else(|| resource(self.path, "documentation token count overflow"))?;
569 if self.tokens > self.limits.max_tokens {
570 return Err(resource(
571 self.path,
572 "documentation aggregate token ceiling exceeded",
573 ));
574 }
575 match token.kind {
576 TokenKind::Left => {
577 forms += 1;
578 if forms > self.limits.max_list_forms {
579 return Err(resource(
580 self.path,
581 "documentation list ceiling exceeded before allocation",
582 ));
583 }
584 depth += 1;
585 head = true;
586 }
587 TokenKind::Right => {
588 depth = depth.saturating_sub(1);
589 head = false;
590 }
591 _ => {
592 if head && depth == 2 {
593 let decoded;
594 let value = if token.kind == TokenKind::QuotedString {
595 decoded = decode_quoted(token.lexeme);
596 decoded.as_str()
597 } else {
598 token.lexeme
599 };
600 if SchematicDocumentationKind::from_head(value).is_some() {
601 rows += 1;
602 if rows > self.limits.max_rows {
603 return Err(resource(
604 self.path,
605 "documentation row ceiling exceeded before span allocation",
606 ));
607 }
608 }
609 }
610 head = false;
611 }
612 }
613 }
614 Ok(())
615 }
616 fn candidates(&mut self, source: &str) -> Result<usize, SourceBundleError> {
619 self.scan(source.len())?;
620 let (mut depth, mut first, mut count) = (0usize, true, 0usize);
621 for token in Lexer::new(source) {
622 let token = token.map_err(|error| sexpr_error(self.path, error))?;
623 self.tokens = self
624 .tokens
625 .checked_add(1)
626 .ok_or_else(|| resource(self.path, "documentation token count overflow"))?;
627 if self.tokens > self.limits.max_tokens {
628 return Err(resource(
629 self.path,
630 "documentation aggregate token ceiling exceeded",
631 ));
632 }
633 match token.kind {
634 TokenKind::Left => {
635 if depth == 1 {
636 count += 1;
637 }
638 depth += 1;
639 }
640 TokenKind::Right => {
641 depth = depth.saturating_sub(1);
642 }
643 _ if depth == 1 => {
644 if first {
645 first = false;
646 } else {
647 count += 1;
648 }
649 }
650 _ => {}
651 }
652 }
653 Ok(count)
654 }
655 fn row(&mut self) -> Result<(), SourceBundleError> {
656 self.rows += 1;
657 if self.rows > self.limits.max_rows {
658 return Err(resource(
659 self.path,
660 "documentation aggregate read ceiling exceeded",
661 ));
662 }
663 Ok(())
664 }
665 fn angle_step(&mut self) -> Result<(), SourceBundleError> {
666 self.angle_steps = self
667 .angle_steps
668 .checked_add(1)
669 .ok_or_else(|| resource(self.path, "documentation native angle step overflow"))?;
670 if self.angle_steps > self.limits.max_native_angle_steps {
671 return Err(resource(
672 self.path,
673 "documentation native angle work ceiling exceeded",
674 ));
675 }
676 Ok(())
677 }
678 fn points(&mut self, count: usize) -> Result<(), SourceBundleError> {
679 self.points = self
680 .points
681 .checked_add(count)
682 .ok_or_else(|| resource(self.path, "documentation point count overflow"))?;
683 if self.points > self.limits.max_points {
684 return Err(resource(
685 self.path,
686 "documentation aggregate point ceiling exceeded",
687 ));
688 }
689 Ok(())
690 }
691 fn members(&mut self, count: usize) -> Result<(), SourceBundleError> {
692 self.members = self
693 .members
694 .checked_add(count)
695 .ok_or_else(|| resource(self.path, "documentation member count overflow"))?;
696 if self.members > self.limits.max_group_members {
697 return Err(resource(
698 self.path,
699 "documentation aggregate member ceiling exceeded",
700 ));
701 }
702 Ok(())
703 }
704}
705struct Fields<'a> {
706 source: &'a str,
707 path: &'a str,
708 spans: Vec<FormSpan>,
709}
710impl<'a> Fields<'a> {
711 fn new(
712 source: &'a str,
713 path: &'a str,
714 budget: &mut Budget<'_>,
715 ) -> Result<Self, SourceBundleError> {
716 budget.preflight(source)?;
717 budget.scan(source.len())?;
718 let spans = scan_form_spans(
719 source,
720 &FormSelector {
721 min_depth: Some(1),
722 max_depth: Some(1),
723 ..Default::default()
724 },
725 )
726 .map_err(|error| sexpr_error(path, error))?;
727 Ok(Self {
728 source,
729 path,
730 spans,
731 })
732 }
733 fn form(&self, key: &str, budget: &mut Budget<'_>) -> Result<Option<Sexp>, SourceBundleError> {
734 let mut matches = self
735 .spans
736 .iter()
737 .filter(|span| span.head.as_deref() == Some(key));
738 let Some(span) = matches.next() else {
739 return Ok(None);
740 };
741 if matches.next().is_some() {
742 return Err(content(self.path, format!("ambiguous documentation {key}")));
743 }
744 let source = &self.source[span.range.clone()];
745 budget.preflight(source)?;
746 if key == "pts" {
747 let count = budget.candidates(source)?;
748 budget.points(count)?;
749 }
750 if key == "members" {
751 let count = budget.candidates(source)?;
752 budget.members(count)?;
753 }
754 budget.scan(source.len())?;
755 parse(source)
756 .map(Some)
757 .map_err(|error| sexpr_error(self.path, error))
758 }
759}
760fn failure(path: &str, kind: SourceBundleErrorKind, reason: impl ToString) -> SourceBundleError {
761 SourceBundleError::new(kind, Some(path), reason.to_string())
762}
763fn facet<T>(
764 result: Result<T, SourceBundleError>,
765) -> Result<Result<T, SourceBundleError>, SourceBundleError> {
766 match result {
767 Err(error) if error.kind != SourceBundleErrorKind::Schematic => Err(error),
768 result => Ok(result),
769 }
770}
771fn content(path: &str, reason: impl ToString) -> SourceBundleError {
772 failure(path, SourceBundleErrorKind::Schematic, reason)
773}
774fn resource(path: &str, reason: impl ToString) -> SourceBundleError {
775 failure(path, SourceBundleErrorKind::ResourceLimit, reason)
776}
777fn sexpr_error(path: &str, error: crate::sexpr::Error) -> SourceBundleError {
778 failure(
779 path,
780 if error.kind == ErrorKind::ResourceLimit {
781 SourceBundleErrorKind::ResourceLimit
782 } else {
783 SourceBundleErrorKind::Schematic
784 },
785 error,
786 )
787}
788fn list(form: &Sexp) -> &[Sexp] {
789 if let Sexp::List(values) = form {
790 values
791 } else {
792 &[]
793 }
794}
795fn text(form: &Sexp) -> Option<&str> {
796 match form {
797 Sexp::Atom(value) | Sexp::Quoted(value) => Some(value),
798 _ => None,
799 }
800}
801fn number(form: Option<&Sexp>, path: &str) -> Result<f64, SourceBundleError> {
802 let value = match form {
803 Some(Sexp::Integer(value)) => *value as f64,
804 Some(Sexp::Float(value)) => *value,
805 _ => return Err(content(path, "documentation numeric scalar required")),
806 };
807 if !value.is_finite() {
808 return Err(content(
809 path,
810 "documentation finite numeric scalar required",
811 ));
812 }
813 Ok(value)
814}
815
816#[cfg(test)]
817mod tests {
818 use super::*;
819 #[test]
820 fn root_uuid_preflight_stops_at_all_root_row_cap_before_later_malformed_input() {
821 let mut budget = Budget::new(
822 "root.kicad_sch",
823 SchematicDocumentationSourceLimits {
824 max_rows: 1,
825 ..Default::default()
826 },
827 );
828 let error = budget
829 .root_rows_before_spans("(kicad_sch (wire) (future_extension) \"unterminated")
830 .unwrap_err();
831 assert_eq!(error.kind, SourceBundleErrorKind::ResourceLimit);
832 assert!(error.message.contains("before span allocation"));
833 }
834}