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

kicad_monkey_core/schematic_bundle/
document.rs

1//! Owned schematic source with transactional, source-preserving mutations.
2
3use super::{
4    SchematicDefinition, parse_schematic_definition_for_import, parse_schematic_definition_text,
5    schematic_error, schematic_limit,
6};
7use crate::sexpr::{
8    Lexer, Patch, Sexp, Token, TokenKind, apply_patches_with_limit, build_with_limit,
9    decode_quoted_with_limit,
10};
11use crate::sexpr_projection::{FormSpan, Selector, scan_form_spans};
12use crate::{SourceBundleError, SourceBundleErrorKind};
13use std::collections::BTreeSet;
14use std::io::{Read, Write};
15use std::ops::Range;
16
17const DEFAULT_SOURCE_PATH: &str = "document.kicad_sch";
18
19/// One owned KiCad schematic source.
20///
21/// Unknown forms remain in the exact source buffer. Typed state is rebuilt on
22/// demand, avoiding a self-referential model and ensuring that every mutation
23/// is semantically reparsed before it replaces the current source.
24#[derive(Clone, Debug)]
25pub struct SchematicDocument {
26    source_path: String,
27    source: String,
28    import_read_only: bool,
29}
30
31/// Explicit import-only opening. The retained compact carrier subset and its
32/// derived connectivity are incomplete whenever `carrier_issues` is nonempty.
33/// The exact document remains readable but cannot be saved or mutated, including
34/// through a clone. This result never enters the strict definition cache.
35#[derive(Clone, Debug)]
36pub struct SchematicImportRead {
37    pub document: SchematicDocument,
38    pub definition: SchematicDefinition,
39    pub carrier_issues: Vec<crate::SchematicCarrierIssue>,
40}
41
42impl SchematicDocument {
43    /// Validate and own one UTF-8 `kicad_sch` source using a virtual filename.
44    pub fn parse(source: String) -> Result<Self, SourceBundleError> {
45        Self::parse_named(DEFAULT_SOURCE_PATH, source)
46    }
47
48    /// Validate and own one UTF-8 `kicad_sch` source with its portable path.
49    pub fn parse_named(
50        source_path: impl Into<String>,
51        source: String,
52    ) -> Result<Self, SourceBundleError> {
53        Self::parse_named_with_definition(source_path, source)
54            .map(|(document, _definition)| document)
55    }
56
57    /// Validate one named source and retain the typed definition produced by
58    /// that exact validation pass.
59    pub fn parse_named_with_definition(
60        source_path: impl Into<String>,
61        source: String,
62    ) -> Result<(Self, SchematicDefinition), SourceBundleError> {
63        let source_path = source_path.into();
64        validate_path(&source_path, usize::MAX)?;
65        let definition = parse_schematic_definition_text(&source, &source_path)?;
66        Ok((
67            Self {
68                source_path,
69                source,
70                import_read_only: false,
71            },
72            definition,
73        ))
74    }
75
76    /// Read exact source for an importer, recovering only malformed scalar-wire
77    /// and junction content rows. All structural/root/other semantic failures
78    /// remain fatal. Even valid input produces a read-only document.
79    pub fn parse_named_for_import_read_only(
80        source_path: impl Into<String>,
81        source: String,
82    ) -> Result<SchematicImportRead, SourceBundleError> {
83        let source_path = source_path.into();
84        validate_path(&source_path, usize::MAX)?;
85        let (definition, carrier_issues) =
86            parse_schematic_definition_for_import(&source, &source_path)?;
87        Ok(SchematicImportRead {
88            document: Self {
89                source_path,
90                source,
91                import_read_only: true,
92            },
93            definition,
94            carrier_issues,
95        })
96    }
97
98    /// Read at most the configured source ceiling plus one sentinel byte.
99    pub fn from_reader(reader: impl Read) -> Result<Self, SourceBundleError> {
100        Self::from_named_reader(DEFAULT_SOURCE_PATH, reader)
101    }
102
103    /// Read and validate one named schematic without an unbounded input copy.
104    pub fn from_named_reader(
105        source_path: impl Into<String>,
106        reader: impl Read,
107    ) -> Result<Self, SourceBundleError> {
108        Self::from_named_reader_with_definition(source_path, reader)
109            .map(|(document, _definition)| document)
110    }
111
112    /// Read, validate, and return the typed definition from the same bounded
113    /// parse rather than reparsing the retained source immediately.
114    pub fn from_named_reader_with_definition(
115        source_path: impl Into<String>,
116        mut reader: impl Read,
117    ) -> Result<(Self, SchematicDefinition), SourceBundleError> {
118        let source_path = source_path.into();
119        validate_path(&source_path, usize::MAX)?;
120        let mut bytes = Vec::new();
121        reader
122            .read_to_end(&mut bytes)
123            .map_err(|error| io_error(&source_path, error))?;
124        let source = String::from_utf8(bytes).map_err(|error| {
125            SourceBundleError::new(
126                SourceBundleErrorKind::Utf8,
127                Some(&source_path),
128                format!(
129                    "source is not UTF-8 at byte {}",
130                    error.utf8_error().valid_up_to()
131                ),
132            )
133        })?;
134        Self::parse_named_with_definition(source_path, source)
135    }
136
137    pub fn source_path(&self) -> &str {
138        &self.source_path
139    }
140
141    pub fn source(&self) -> &str {
142        &self.source
143    }
144
145    /// Read close-to-format paper data from this exact owned source.
146    pub fn paper(&self) -> Result<crate::KiCadPaper, crate::sexpr::Error> {
147        crate::schematic_page::schematic_paper(&self.source)
148    }
149
150    pub fn into_source(self) -> String {
151        self.source
152    }
153
154    /// Rebuild the promoted typed model over the current exact source.
155    pub fn definition(&self) -> Result<SchematicDefinition, SourceBundleError> {
156        parse_schematic_definition_text(&self.source, &self.source_path)
157    }
158
159    /// Write the current source verbatim after checking the output ceiling.
160    pub fn write_to(&self, mut writer: impl Write) -> Result<(), SourceBundleError> {
161        self.check_output_source()?;
162        writer
163            .write_all(self.source.as_bytes())
164            .map_err(|error| io_error(&self.source_path, error))
165    }
166
167    /// Replace one existing property on one unambiguous placed symbol UUID.
168    pub fn set_symbol_property(
169        &mut self,
170        symbol_uuid: &str,
171        name: &str,
172        value: &str,
173    ) -> Result<bool, SourceBundleError> {
174        let index = self.mutation_index()?;
175        let symbol = index.unique_symbol(symbol_uuid, &self.source_path)?;
176        let property = unique_property(symbol, name, &self.source_path)?.ok_or_else(|| {
177            schematic_source_error(&self.source_path, "schematic symbol property was not found")
178        })?;
179        if property.value == value {
180            return Ok(false);
181        }
182        let replacement = quoted(value, usize::MAX, &self.source_path)?;
183        self.commit_patch(Patch::new(
184            property.value_range.start,
185            property.value_range.end,
186            replacement,
187        ))
188    }
189
190    /// Update or insert one property on one unambiguous placed symbol UUID.
191    pub fn upsert_symbol_property(
192        &mut self,
193        symbol_uuid: &str,
194        name: &str,
195        value: &str,
196    ) -> Result<bool, SourceBundleError> {
197        let index = self.mutation_index()?;
198        let symbol = index.unique_symbol(symbol_uuid, &self.source_path)?;
199        if unique_property(symbol, name, &self.source_path)?.is_some() {
200            return self.set_symbol_property(symbol_uuid, name, value);
201        }
202        let form = inserted_property_form(name, value, usize::MAX, &self.source_path)?;
203        let (offset, replacement) = insertion(&self.source, &symbol.span, &form);
204        self.commit_patch(Patch::new(offset, offset, replacement))
205    }
206
207    /// Remove one property from one unambiguous placed symbol UUID.
208    pub fn remove_symbol_property(
209        &mut self,
210        symbol_uuid: &str,
211        name: &str,
212    ) -> Result<bool, SourceBundleError> {
213        self.check_output_source()?;
214        let index = self.mutation_index()?;
215        let symbol = index.unique_symbol(symbol_uuid, &self.source_path)?;
216        let Some(property) = unique_property(symbol, name, &self.source_path)? else {
217            return Ok(false);
218        };
219        self.commit_patch(Patch::new(
220            property.source_range.start,
221            property.source_range.end,
222            "",
223        ))
224    }
225
226    fn mutation_index(&self) -> Result<MutationIndex, SourceBundleError> {
227        self.check_output_source()?;
228        MutationIndex::build(&self.source, &self.source_path)
229    }
230
231    fn check_output_source(&self) -> Result<(), SourceBundleError> {
232        if self.import_read_only {
233            Err(schematic_source_error(
234                &self.source_path,
235                "import-read-only schematic cannot be mutated or saved",
236            ))
237        } else {
238            Ok(())
239        }
240    }
241
242    fn commit_patch(&mut self, patch: Patch<'_>) -> Result<bool, SourceBundleError> {
243        self.check_output_source()?;
244        let candidate = apply_patches_with_limit(&self.source, &[patch], usize::MAX)
245            .map_err(|error| schematic_error(&self.source_path, error))?;
246        parse_schematic_definition_text(&candidate, &self.source_path)?;
247        self.source = candidate;
248        Ok(true)
249    }
250}
251
252#[derive(Debug)]
253struct MutationIndex {
254    symbols: Vec<SymbolRecord>,
255}
256
257impl MutationIndex {
258    fn build(source: &str, source_path: &str) -> Result<Self, SourceBundleError> {
259        let paths = [
260            vec!["kicad_sch".to_owned(), "symbol".to_owned()],
261            vec![
262                "kicad_sch".to_owned(),
263                "symbol".to_owned(),
264                "uuid".to_owned(),
265            ],
266            vec![
267                "kicad_sch".to_owned(),
268                "symbol".to_owned(),
269                "property".to_owned(),
270            ],
271        ]
272        .into_iter()
273        .collect::<BTreeSet<_>>();
274        let spans = scan_form_spans(
275            source,
276            &Selector {
277                paths: Some(paths),
278                min_depth: Some(1),
279                max_depth: Some(2),
280                ..Selector::default()
281            },
282        )
283        .map_err(|error| schematic_error(source_path, error))?;
284        let mut symbols: Vec<SymbolRecord> = Vec::new();
285        for span in spans {
286            if span.depth == 1 {
287                symbols.push(SymbolRecord {
288                    span,
289                    uuid: String::new(),
290                    uuid_seen: false,
291                    properties: Vec::new(),
292                });
293                continue;
294            }
295            let symbol = symbols.last_mut().ok_or_else(|| {
296                schematic_source_error(source_path, "symbol child has no owning placed symbol")
297            })?;
298            if span.range.end >= symbol.span.range.end {
299                return Err(schematic_source_error(
300                    source_path,
301                    "symbol child falls outside its owning placed symbol",
302                ));
303            }
304            match span.head.as_deref() {
305                Some("uuid") => {
306                    let value = scalar_form(source, &span, source_path)?;
307                    if symbol.uuid_seen {
308                        return Err(schematic_source_error(
309                            source_path,
310                            "placed symbol has ambiguous uuid forms",
311                        ));
312                    }
313                    symbol.uuid = value;
314                    symbol.uuid_seen = true;
315                }
316                Some("property") => {
317                    symbol
318                        .properties
319                        .push(property_form(source, &span, source_path)?)
320                }
321                _ => {}
322            }
323        }
324        Ok(Self { symbols })
325    }
326
327    fn unique_symbol(
328        &self,
329        symbol_uuid: &str,
330        source_path: &str,
331    ) -> Result<&SymbolRecord, SourceBundleError> {
332        if symbol_uuid.is_empty() {
333            return Err(schematic_source_error(
334                source_path,
335                "schematic symbol UUID cannot be empty",
336            ));
337        }
338        let mut matches = self
339            .symbols
340            .iter()
341            .filter(|symbol| symbol.uuid == symbol_uuid);
342        let symbol = matches.next().ok_or_else(|| {
343            schematic_source_error(source_path, "schematic symbol UUID was not found")
344        })?;
345        if matches.next().is_some() {
346            return Err(schematic_source_error(
347                source_path,
348                "schematic symbol UUID is ambiguous",
349            ));
350        }
351        Ok(symbol)
352    }
353}
354
355#[derive(Debug)]
356struct SymbolRecord {
357    span: FormSpan,
358    uuid: String,
359    uuid_seen: bool,
360    properties: Vec<PropertyRecord>,
361}
362
363#[derive(Debug)]
364struct PropertyRecord {
365    name: String,
366    value: String,
367    source_range: Range<usize>,
368    value_range: Range<usize>,
369}
370
371fn unique_property<'a>(
372    symbol: &'a SymbolRecord,
373    name: &str,
374    source_path: &str,
375) -> Result<Option<&'a PropertyRecord>, SourceBundleError> {
376    let mut matches = symbol
377        .properties
378        .iter()
379        .filter(|property| property.name == name);
380    let first = matches.next();
381    if matches.next().is_some() {
382        return Err(schematic_source_error(
383            source_path,
384            "schematic symbol property name is ambiguous",
385        ));
386    }
387    Ok(first)
388}
389
390fn scalar_form(
391    source: &str,
392    span: &FormSpan,
393    source_path: &str,
394) -> Result<String, SourceBundleError> {
395    let text = span
396        .text(source)
397        .map_err(|error| schematic_error(source_path, error))?;
398    let mut lexer = Lexer::new(text);
399    expect(&mut lexer, TokenKind::Left, source_path)?;
400    next_scalar(&mut lexer, source_path, usize::MAX)?;
401    next_scalar(&mut lexer, source_path, usize::MAX)
402}
403
404fn property_form(
405    source: &str,
406    span: &FormSpan,
407    source_path: &str,
408) -> Result<PropertyRecord, SourceBundleError> {
409    let text = span
410        .text(source)
411        .map_err(|error| schematic_error(source_path, error))?;
412    let mut lexer = Lexer::new(text);
413    expect(&mut lexer, TokenKind::Left, source_path)?;
414    next_scalar(&mut lexer, source_path, usize::MAX)?;
415    let name = next_scalar_token(&mut lexer, source_path)?;
416    let value = next_scalar_token(&mut lexer, source_path)?;
417    Ok(PropertyRecord {
418        name: decode(name.clone(), usize::MAX, source_path)?,
419        value: decode(value.clone(), usize::MAX, source_path)?,
420        source_range: span.range.clone(),
421        value_range: (span.range.start + value.position.offset)
422            ..(span.range.start + value.position.offset + value.lexeme.len()),
423    })
424}
425
426fn next_scalar(
427    lexer: &mut Lexer<'_>,
428    source_path: &str,
429    max_bytes: usize,
430) -> Result<String, SourceBundleError> {
431    let token = next_scalar_token(lexer, source_path)?;
432    decode(token, max_bytes, source_path)
433}
434
435fn next_scalar_token<'a>(
436    lexer: &mut Lexer<'a>,
437    source_path: &str,
438) -> Result<Token<'a>, SourceBundleError> {
439    let token = lexer
440        .next()
441        .transpose()
442        .map_err(|error| schematic_error(source_path, error))?
443        .ok_or_else(|| schematic_source_error(source_path, "expected scalar value"))?;
444    if matches!(token.kind, TokenKind::Left | TokenKind::Right) {
445        return Err(schematic_source_error(source_path, "expected scalar value"));
446    }
447    Ok(token)
448}
449
450fn expect(
451    lexer: &mut Lexer<'_>,
452    expected: TokenKind,
453    source_path: &str,
454) -> Result<(), SourceBundleError> {
455    let token = lexer
456        .next()
457        .transpose()
458        .map_err(|error| schematic_error(source_path, error))?
459        .ok_or_else(|| schematic_source_error(source_path, "expected schematic form"))?;
460    if token.kind != expected {
461        return Err(schematic_source_error(
462            source_path,
463            "expected schematic form",
464        ));
465    }
466    Ok(())
467}
468
469fn decode(
470    token: Token<'_>,
471    max_bytes: usize,
472    source_path: &str,
473) -> Result<String, SourceBundleError> {
474    if token.kind != TokenKind::QuotedString {
475        return Ok(token.lexeme.to_owned());
476    }
477    decode_quoted_with_limit(token.lexeme, max_bytes).ok_or_else(|| {
478        schematic_limit(
479            source_path,
480            "decoded scalar exceeds max_decoded_string_bytes",
481        )
482    })
483}
484
485fn quoted(
486    value: &str,
487    max_output_bytes: usize,
488    source_path: &str,
489) -> Result<String, SourceBundleError> {
490    build_with_limit(&Sexp::Quoted(value.to_owned()), max_output_bytes)
491        .map_err(|error| schematic_error(source_path, error))
492}
493
494fn inserted_property_form(
495    name: &str,
496    value: &str,
497    max_output_bytes: usize,
498    source_path: &str,
499) -> Result<String, SourceBundleError> {
500    let name = quoted(name, max_output_bytes, source_path)?;
501    let value = quoted(value, max_output_bytes, source_path)?;
502    let required = "(property   (at 0 0 0))"
503        .len()
504        .checked_add(name.len())
505        .and_then(|bytes| bytes.checked_add(value.len()))
506        .ok_or_else(|| schematic_limit(source_path, "inserted property byte count overflows"))?;
507    let mut form = String::with_capacity(required);
508    form.push_str("(property ");
509    form.push_str(&name);
510    form.push(' ');
511    form.push_str(&value);
512    form.push_str(" (at 0 0 0))");
513    debug_assert_eq!(form.len(), required);
514    Ok(form)
515}
516
517fn insertion(source: &str, symbol: &FormSpan, form: &str) -> (usize, String) {
518    let close = symbol.range.end.saturating_sub(1);
519    let line_start = source[..close].rfind('\n').map_or(0, |offset| offset + 1);
520    let close_prefix = &source[line_start..close];
521    let newline = if source.contains("\r\n") {
522        "\r\n"
523    } else {
524        "\n"
525    };
526    let symbol_line_start = source[..symbol.range.start]
527        .rfind('\n')
528        .map_or(0, |offset| offset + 1);
529    let symbol_indent = source[symbol_line_start..symbol.range.start]
530        .chars()
531        .take_while(|character| character.is_whitespace())
532        .collect::<String>();
533    let child_indent = format!("{symbol_indent}  ");
534    if close_prefix.trim().is_empty() {
535        (line_start, format!("{child_indent}{form}{newline}"))
536    } else {
537        (
538            close,
539            format!("{newline}{child_indent}{form}{newline}{symbol_indent}"),
540        )
541    }
542}
543
544pub(super) fn validate_path(_path: &str, _max_bytes: usize) -> Result<(), SourceBundleError> {
545    Ok(())
546}
547
548fn schematic_source_error(path: &str, message: impl Into<String>) -> SourceBundleError {
549    SourceBundleError::new(SourceBundleErrorKind::Schematic, Some(path), message)
550}
551
552fn io_error(path: &str, error: std::io::Error) -> SourceBundleError {
553    schematic_source_error(path, format!("schematic source I/O failed: {error}"))
554}