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

kicad_monkey_core/
source_bundle.rs

1//! Named, byte-preserving multi-file inputs for the schematic compiler.
2
3use kicad_monkey_contracts::generated::source_bundle_manifest::{
4    SourceBundleManifestA0, SourceBundleSource, SourceKind,
5};
6use kicad_monkey_contracts::validate_source_bundle_manifest_contract;
7use sha2::{Digest, Sha256};
8use std::collections::BTreeMap;
9use std::fmt;
10
11/// One exact caller-supplied byte buffer after manifest validation.
12#[derive(Clone, Debug, Eq, PartialEq)]
13pub struct SourceFile {
14    path: String,
15    kind: SourceKind,
16    bytes: Vec<u8>,
17}
18
19impl SourceFile {
20    pub fn path(&self) -> &str {
21        &self.path
22    }
23
24    pub fn kind(&self) -> SourceKind {
25        self.kind
26    }
27
28    pub fn bytes(&self) -> &[u8] {
29        &self.bytes
30    }
31
32    pub fn text(&self) -> Result<&str, SourceBundleError> {
33        std::str::from_utf8(&self.bytes).map_err(|error| {
34            SourceBundleError::new(
35                SourceBundleErrorKind::Utf8,
36                Some(&self.path),
37                format!("source is not UTF-8 at byte {}", error.valid_up_to()),
38            )
39        })
40    }
41}
42
43/// Validated source inventory with exact source bytes owned once.
44#[derive(Clone, Debug)]
45pub struct SourceBundle {
46    root_schematic_path: String,
47    project_path: Option<String>,
48    sources: BTreeMap<String, SourceFile>,
49    total_bytes: usize,
50}
51
52impl SourceBundle {
53    /// Pair a generated manifest with separate byte slots and validate the boundary.
54    pub fn from_manifest(
55        manifest: SourceBundleManifestA0,
56        mut buffers: Vec<Vec<u8>>,
57    ) -> Result<Self, SourceBundleError> {
58        validate_source_bundle_manifest_contract(&manifest).map_err(|error| {
59            SourceBundleError::new(SourceBundleErrorKind::Contract, None, error.to_string())
60        })?;
61        validate_bundle_cardinality(manifest.sources.len(), buffers.len())?;
62
63        let root_schematic_path = normalize_bundle_path(&manifest.root_schematic_path)?;
64        let project_path = manifest
65            .project_path
66            .as_deref()
67            .map(normalize_bundle_path)
68            .transpose()?;
69        let (sources, total_bytes) = assemble_sources(manifest.sources, &mut buffers)?;
70
71        require_source_kind(&sources, &root_schematic_path, SourceKind::Schematic)?;
72        if let Some(path) = project_path.as_deref() {
73            require_source_kind(&sources, path, SourceKind::Project)?;
74        }
75
76        Ok(Self {
77            root_schematic_path,
78            project_path,
79            sources,
80            total_bytes,
81        })
82    }
83
84    pub fn root_schematic_path(&self) -> &str {
85        &self.root_schematic_path
86    }
87
88    pub fn project_path(&self) -> Option<&str> {
89        self.project_path.as_deref()
90    }
91
92    pub fn total_bytes(&self) -> usize {
93        self.total_bytes
94    }
95
96    pub fn sources(&self) -> impl ExactSizeIterator<Item = &SourceFile> {
97        self.sources.values()
98    }
99
100    pub fn source(&self, path: &str) -> Result<Option<&SourceFile>, SourceBundleError> {
101        let path = normalize_bundle_path(path)?;
102        Ok(self.sources.get(&path))
103    }
104
105    pub fn root_schematic(&self) -> &SourceFile {
106        &self.sources[&self.root_schematic_path]
107    }
108
109    pub fn project(&self) -> Option<&SourceFile> {
110        self.project_path
111            .as_ref()
112            .and_then(|path| self.sources.get(path))
113    }
114
115    pub(crate) fn bundle_identity_sha256(&self) -> [u8; 32] {
116        let mut hasher = Sha256::new();
117        hash_identity_field(&mut hasher, self.root_schematic_path.as_bytes());
118        match &self.project_path {
119            Some(path) => {
120                hasher.update([1]);
121                hash_identity_field(&mut hasher, path.as_bytes());
122            }
123            None => hasher.update([0]),
124        }
125        hash_identity_field(&mut hasher, &self.sources.len().to_le_bytes());
126        for source in self.sources.values() {
127            hash_identity_field(&mut hasher, source.path().as_bytes());
128            hash_identity_field(&mut hasher, source_kind_identity(source.kind()));
129            hash_identity_field(&mut hasher, source.bytes());
130        }
131        hasher.finalize().into()
132    }
133
134    pub(crate) fn resolve_schematic(
135        &self,
136        parent_path: &str,
137        reference: &str,
138    ) -> Result<&SourceFile, SourceBundleError> {
139        let resolved = resolve_relative_path(parent_path, reference)?;
140        let source = self.sources.get(&resolved).ok_or_else(|| {
141            SourceBundleError::new(
142                SourceBundleErrorKind::MissingSource,
143                Some(&resolved),
144                "referenced schematic is absent from the source bundle",
145            )
146        })?;
147        if source.kind != SourceKind::Schematic {
148            return Err(SourceBundleError::new(
149                SourceBundleErrorKind::Kind,
150                Some(&resolved),
151                "referenced sheet source is not classified as schematic",
152            ));
153        }
154        Ok(source)
155    }
156}
157
158fn source_kind_identity(kind: SourceKind) -> &'static [u8] {
159    match kind {
160        SourceKind::Project => b"project",
161        SourceKind::Schematic => b"schematic",
162        SourceKind::SymbolLibrary => b"symbol_library",
163        SourceKind::SymbolTable => b"symbol_table",
164        SourceKind::Worksheet => b"worksheet",
165        SourceKind::Other => b"other",
166    }
167}
168
169fn hash_identity_field(hasher: &mut Sha256, value: &[u8]) {
170    hasher.update((value.len() as u128).to_le_bytes());
171    hasher.update(value);
172}
173
174fn validate_bundle_cardinality(
175    descriptor_count: usize,
176    buffer_count: usize,
177) -> Result<(), SourceBundleError> {
178    if descriptor_count == 0 {
179        return Err(SourceBundleError::new(
180            SourceBundleErrorKind::Contract,
181            None,
182            "a source bundle needs at least its root schematic",
183        ));
184    }
185    if buffer_count != descriptor_count {
186        return Err(SourceBundleError::new(
187            SourceBundleErrorKind::Slot,
188            None,
189            "the byte-slot count must exactly equal the source descriptor count",
190        ));
191    }
192    Ok(())
193}
194
195fn assemble_sources(
196    descriptors: Vec<SourceBundleSource>,
197    buffers: &mut [Vec<u8>],
198) -> Result<(BTreeMap<String, SourceFile>, usize), SourceBundleError> {
199    let mut used_slots = vec![false; buffers.len()];
200    let mut sources = BTreeMap::new();
201    let mut total_bytes = 0_usize;
202    for descriptor in descriptors {
203        let (path, source, byte_count) = consume_descriptor(descriptor, buffers, &mut used_slots)?;
204        // Each byte count is the length of a distinct buffer held in memory,
205        // so the sum stays within the address space.
206        total_bytes += byte_count;
207        if sources.insert(path.clone(), source).is_some() {
208            return Err(SourceBundleError::new(
209                SourceBundleErrorKind::Path,
210                Some(&path),
211                "normalized source paths must be unique",
212            ));
213        }
214    }
215    require_all_slots(&used_slots)?;
216    Ok((sources, total_bytes))
217}
218
219fn consume_descriptor(
220    descriptor: SourceBundleSource,
221    buffers: &mut [Vec<u8>],
222    used_slots: &mut [bool],
223) -> Result<(String, SourceFile, usize), SourceBundleError> {
224    let path = normalize_bundle_path(&descriptor.path)?;
225    validate_kind_suffix(&descriptor, &path)?;
226    let slot = descriptor.slot.0 as usize;
227    if slot >= buffers.len() || used_slots[slot] {
228        return Err(SourceBundleError::new(
229            SourceBundleErrorKind::Slot,
230            Some(&path),
231            "source slots must be unique and in range",
232        ));
233    }
234    let declared_bytes = descriptor.source_bytes.parse::<usize>().map_err(|_| {
235        SourceBundleError::new(
236            SourceBundleErrorKind::Contract,
237            Some(&path),
238            "source_bytes must be a platform-sized decimal string",
239        )
240    })?;
241    let actual_bytes = buffers[slot].len();
242    if declared_bytes != actual_bytes {
243        return Err(SourceBundleError::new(
244            SourceBundleErrorKind::Contract,
245            Some(&path),
246            "source_bytes does not match its byte slot",
247        ));
248    }
249    used_slots[slot] = true;
250    let source = SourceFile {
251        path: path.clone(),
252        kind: descriptor.kind,
253        bytes: std::mem::take(&mut buffers[slot]),
254    };
255    Ok((path, source, actual_bytes))
256}
257
258fn require_all_slots(used_slots: &[bool]) -> Result<(), SourceBundleError> {
259    if used_slots.iter().all(|used| *used) {
260        Ok(())
261    } else {
262        Err(SourceBundleError::new(
263            SourceBundleErrorKind::Slot,
264            None,
265            "every byte slot must have exactly one descriptor",
266        ))
267    }
268}
269
270fn validate_kind_suffix(
271    descriptor: &SourceBundleSource,
272    path: &str,
273) -> Result<(), SourceBundleError> {
274    // KiCad finds a project and its library tables by name. It reads a sheet,
275    // library or drawing sheet file under whatever name refers to it: a sheet
276    // loads its `Sheetfile` as written
277    // (eeschema/sch_io/kicad_sexpr/sch_io_kicad_sexpr.cpp:264-283), and a
278    // file it cannot read there is an empty page, not a refused project.
279    let valid = match descriptor.kind {
280        SourceKind::Project => path_ends_with_ascii_case(path, ".kicad_pro"),
281        SourceKind::SymbolTable => {
282            path_ends_with_ascii_case(path, "sym-lib-table")
283                || path_ends_with_ascii_case(path, "fp-lib-table")
284        }
285        SourceKind::Schematic
286        | SourceKind::SymbolLibrary
287        | SourceKind::Worksheet
288        | SourceKind::Other => true,
289    };
290    if valid {
291        Ok(())
292    } else {
293        Err(SourceBundleError::new(
294            SourceBundleErrorKind::Kind,
295            Some(path),
296            "source kind does not match its KiCad filename",
297        ))
298    }
299}
300
301fn path_ends_with_ascii_case(path: &str, suffix: &str) -> bool {
302    path.get(path.len().saturating_sub(suffix.len())..)
303        .is_some_and(|value| value.eq_ignore_ascii_case(suffix))
304}
305
306fn require_source_kind(
307    sources: &BTreeMap<String, SourceFile>,
308    path: &str,
309    kind: SourceKind,
310) -> Result<(), SourceBundleError> {
311    let source = sources.get(path).ok_or_else(|| {
312        SourceBundleError::new(
313            SourceBundleErrorKind::MissingSource,
314            Some(path),
315            "manifest entry path is absent from the source inventory",
316        )
317    })?;
318    if source.kind == kind {
319        Ok(())
320    } else {
321        Err(SourceBundleError::new(
322            SourceBundleErrorKind::Kind,
323            Some(path),
324            "manifest entry path has the wrong source kind",
325        ))
326    }
327}
328
329pub(crate) fn resolve_relative_path(
330    parent_path: &str,
331    reference: &str,
332) -> Result<String, SourceBundleError> {
333    let parent = normalize_bundle_path(parent_path)?;
334    let directory = parent
335        .rsplit_once('/')
336        .map_or("", |(directory, _)| directory);
337    let joined = if directory.is_empty() {
338        reference.to_owned()
339    } else {
340        format!("{directory}/{reference}")
341    };
342    normalize_bundle_path(&joined)
343}
344
345pub(crate) fn normalize_bundle_path(value: &str) -> Result<String, SourceBundleError> {
346    if value.is_empty() {
347        return Err(invalid_path_text(value));
348    }
349    if value.contains('\0') {
350        return Err(invalid_path_text(value));
351    }
352    let portable = value.replace('\\', "/");
353    if portable.starts_with('/') {
354        return Err(non_relative_path(value));
355    }
356    if portable
357        .split('/')
358        .next()
359        .is_some_and(|part| part.contains(':'))
360    {
361        return Err(non_relative_path(value));
362    }
363    normalize_path_parts(&portable, value)
364}
365
366fn normalize_path_parts(portable: &str, original: &str) -> Result<String, SourceBundleError> {
367    let mut parts = Vec::new();
368    for part in portable.split('/') {
369        match part {
370            "" | "." => {}
371            ".." => pop_path_part(&mut parts, original)?,
372            _ => parts.push(part),
373        }
374    }
375    if parts.is_empty() {
376        return Err(SourceBundleError::new(
377            SourceBundleErrorKind::Path,
378            Some(original),
379            "source path resolves to the bundle root",
380        ));
381    }
382    Ok(parts.join("/"))
383}
384
385fn pop_path_part(parts: &mut Vec<&str>, original: &str) -> Result<(), SourceBundleError> {
386    if parts.pop().is_none() {
387        Err(SourceBundleError::new(
388            SourceBundleErrorKind::Path,
389            Some(original),
390            "source path escapes the bundle root",
391        ))
392    } else {
393        Ok(())
394    }
395}
396
397fn invalid_path_text(value: &str) -> SourceBundleError {
398    SourceBundleError::new(
399        SourceBundleErrorKind::Path,
400        Some(value),
401        "source path is empty or contains NUL",
402    )
403}
404
405fn non_relative_path(value: &str) -> SourceBundleError {
406    SourceBundleError::new(
407        SourceBundleErrorKind::Path,
408        Some(value),
409        "source paths must be relative portable paths",
410    )
411}
412
413/// Stable category for source-boundary diagnostics.
414#[derive(Clone, Copy, Debug, Eq, PartialEq)]
415pub enum SourceBundleErrorKind {
416    Contract,
417    ResourceLimit,
418    Path,
419    Slot,
420    MissingSource,
421    Kind,
422    Utf8,
423    Project,
424    Schematic,
425    HierarchyCycle,
426}
427
428/// Source-bundle or hierarchy preparation failure.
429#[derive(Clone, Debug, Eq, PartialEq)]
430pub struct SourceBundleError {
431    pub kind: SourceBundleErrorKind,
432    pub source_path: Option<String>,
433    pub message: String,
434}
435
436impl SourceBundleError {
437    pub(crate) fn new(
438        kind: SourceBundleErrorKind,
439        source_path: Option<&str>,
440        message: impl Into<String>,
441    ) -> Self {
442        Self {
443            kind,
444            source_path: source_path.map(str::to_owned),
445            message: message.into(),
446        }
447    }
448}
449
450impl fmt::Display for SourceBundleError {
451    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
452        if let Some(path) = &self.source_path {
453            write!(formatter, "{:?} in {path}: {}", self.kind, self.message)
454        } else {
455            write!(formatter, "{:?}: {}", self.kind, self.message)
456        }
457    }
458}
459
460impl std::error::Error for SourceBundleError {}