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

kicad_monkey_core/library_edits/
symbols.rs

1//! Exact selected-symbol edits, independent of application property policy.
2
3use super::{Error, LibraryEdit, finish, invalid, root_and_spans};
4use crate::sexpr::{Lexer, Patch, Sexp, Token, TokenKind, build_with_limit, decode_quoted};
5use crate::sexpr_projection::FormSpan;
6use crate::symbol_authoring::{
7    AuthoredSymbol, AuthoredSymbolLibrary, AuthoredSymbolProperty, SymbolAuthoringLimits,
8};
9use std::collections::HashSet;
10
11/// One direct Source property, including its exact decoded spelling.
12#[derive(Clone, Debug, Eq, PartialEq)]
13pub struct SymbolPropertyValue {
14    pub name: String,
15    pub value: String,
16}
17
18/// An explicit update or insertion selected by the caller.
19///
20/// `Some(existing_name)` must identify exactly one direct Source property; only
21/// its value scalar is changed, using `property.value`. Its name, presentation,
22/// private flag and unknown forms are retained. `None` inserts the complete
23/// typed property and refuses an existing exact name. Case-fold matching,
24/// default presentation and application metadata policy belong to the caller.
25#[derive(Clone, Debug)]
26pub struct SymbolPropertyUpdate<'a> {
27    pub existing_name: Option<&'a str>,
28    pub property: &'a AuthoredSymbolProperty,
29}
30
31/// Read only direct properties of one uniquely and exactly named root symbol.
32/// Duplicates are returned in Source order so the caller cannot mistake an
33/// ambiguous property for a unique match. Inherited properties are not merged.
34pub fn symbol_property_values(
35    source: &str,
36    symbol_name: &str,
37) -> Result<Vec<SymbolPropertyValue>, Error> {
38    let (_, spans) = root_and_spans(source, &["kicad_symbol_lib"])?;
39    let symbol = unique_symbol(source, &spans, symbol_name)?;
40    Ok(properties(source, &spans, symbol)?
41        .into_iter()
42        .map(|property| property.value)
43        .collect())
44}
45
46/// Prepare every requested edit before patching one selected symbol. Existing
47/// property values are byte patches; inserted properties use the existing
48/// typed symbol authoring validator and writer. Unknown and unselected bytes
49/// survive, including other members of a complete library.
50pub fn upsert_symbol_properties(
51    source: &str,
52    symbol_name: &str,
53    updates: &[SymbolPropertyUpdate<'_>],
54    limits: SymbolAuthoringLimits,
55) -> Result<LibraryEdit, Error> {
56    let (_, spans) = root_and_spans(source, &["kicad_symbol_lib"])?;
57    let symbol = unique_symbol(source, &spans, symbol_name)?;
58    let existing = properties(source, &spans, symbol)?;
59    let mut selected = HashSet::new();
60    let mut names = existing
61        .iter()
62        .map(|property| property.value.name.as_str())
63        .collect::<HashSet<_>>();
64    let mut patches = Vec::new();
65    let mut inserted = Vec::new();
66    for update in updates {
67        if update.property.value.contains('\0') {
68            return Err(invalid("Property value contains a NUL character"));
69        }
70        if let Some(name) = update.existing_name {
71            if !selected.insert(name) {
72                return Err(invalid("A property was selected more than once"));
73            }
74            let matches = existing
75                .iter()
76                .filter(|property| property.value.name == name)
77                .collect::<Vec<_>>();
78            let [property] = matches.as_slice() else {
79                return Err(invalid("Selected Source property is absent or ambiguous"));
80            };
81            if property.value.value != update.property.value {
82                patches.push(Patch::new(
83                    property.value_range.start,
84                    property.value_range.end,
85                    build_with_limit(
86                        &Sexp::Quoted(update.property.value.clone()),
87                        limits.max_output_bytes,
88                    )?,
89                ));
90            }
91        } else {
92            if !names.insert(update.property.name.as_str()) {
93                return Err(invalid("Inserted property name already exists"));
94            }
95            inserted.push(update.property.clone());
96        }
97    }
98    if !inserted.is_empty() {
99        let text = authored_properties(inserted, limits)?;
100        let offset = direct_children(&spans, symbol)
101            .find(|span| span.head.as_deref() == Some("symbol"))
102            .map_or(symbol.range.end - 1, |span| span.range.start);
103        patches.push(Patch::new(offset, offset, text));
104    }
105    finish(source, &patches, limits.max_output_bytes)
106}
107
108/// Materialize the selected positive unit as unit 1 in one symbol's exact
109/// inheritance chain. Unit 0 and all body styles survive. Other recognized
110/// positive units are removed; unknown/non-owned forms and unrelated library
111/// members retain their exact bytes. Source identifiers are exact decoded
112/// names; no implicit aliases or case-fold lookup are performed.
113///
114/// Unit 1 is an exact no-op after validating the unique selected root, matching
115/// the existing remote placement convention. Other selections require an
116/// unambiguous, complete, acyclic parent chain and at least one matching unit.
117/// This does not flatten inheritance, rename root symbols or project geometry.
118pub fn materialize_symbol_unit(
119    source: &str,
120    symbol_name: &str,
121    selected_unit: u32,
122    max_output_bytes: usize,
123) -> Result<LibraryEdit, Error> {
124    if selected_unit == 0 {
125        return Err(invalid("Selected unit must be positive"));
126    }
127    let (_, spans) = root_and_spans(source, &["kicad_symbol_lib"])?;
128    let selected = unique_symbol(source, &spans, symbol_name)?;
129    if selected_unit == 1 {
130        return finish(source, &[], max_output_bytes);
131    }
132    let chain = inheritance_chain(source, &spans, selected)?;
133    let mut patches = Vec::new();
134    let mut found = false;
135    for symbol in chain {
136        let name = header_scalar(source, symbol, 0)?.0;
137        let owner = crate::symbol_library::item_prefix(&name, symbol.start)?;
138        let mut retained_names = HashSet::new();
139        for child in
140            direct_children(&spans, symbol).filter(|span| span.head.as_deref() == Some("symbol"))
141        {
142            let (child_name, range) = header_scalar(source, child, 0)?;
143            let Some((prefix, unit, style)) = owned_unit(&owner, &child_name) else {
144                if !retained_names.insert(child_name.replace("{slash}", "/")) {
145                    return Err(invalid("Retained symbol body name is ambiguous"));
146                }
147                continue;
148            };
149            if unit != 0 && unit != selected_unit {
150                patches.push(Patch::new(child.range.start, child.range.end, ""));
151                continue;
152            }
153            let next = if unit == selected_unit {
154                found = true;
155                format!("{prefix}_1_{style}")
156            } else {
157                child_name.clone()
158            };
159            if !retained_names.insert(next.replace("{slash}", "/")) {
160                return Err(invalid("Materialized symbol body name is ambiguous"));
161            }
162            if next != child_name {
163                patches.push(Patch::new(
164                    range.start,
165                    range.end,
166                    build_with_limit(&Sexp::Quoted(next), max_output_bytes)?,
167                ));
168            }
169        }
170    }
171    if !found {
172        return Err(invalid(
173            "Selected unit was not found in the inheritance chain",
174        ));
175    }
176    finish(source, &patches, max_output_bytes)
177}
178
179struct Property {
180    value: SymbolPropertyValue,
181    value_range: std::ops::Range<usize>,
182}
183
184fn properties(source: &str, spans: &[FormSpan], symbol: &FormSpan) -> Result<Vec<Property>, Error> {
185    direct_children(spans, symbol)
186        .filter(|span| span.head.as_deref() == Some("property"))
187        .map(|span| {
188            let (name, _) = header_scalar(source, span, 0)?;
189            let (value, value_range) = header_scalar(source, span, 1)?;
190            Ok(Property {
191                value: SymbolPropertyValue { name, value },
192                value_range,
193            })
194        })
195        .collect()
196}
197
198fn direct_children<'a>(
199    spans: &'a [FormSpan],
200    parent: &'a FormSpan,
201) -> impl Iterator<Item = &'a FormSpan> {
202    spans.iter().filter(move |span| {
203        span.depth == parent.depth + 1
204            && span.range.start > parent.range.start
205            && span.range.end < parent.range.end
206    })
207}
208
209fn unique_symbol<'a>(
210    source: &str,
211    spans: &'a [FormSpan],
212    name: &str,
213) -> Result<&'a FormSpan, Error> {
214    let mut matched = None;
215    for span in spans
216        .iter()
217        .filter(|span| span.depth == 1 && span.head.as_deref() == Some("symbol"))
218    {
219        if header_scalar(source, span, 0)?.0 == name {
220            if matched.is_some() {
221                return Err(invalid("Selected root symbol name is ambiguous"));
222            }
223            matched = Some(span);
224        }
225    }
226    matched.ok_or_else(|| invalid("Selected root symbol is absent"))
227}
228
229fn inheritance_chain<'a>(
230    source: &str,
231    spans: &'a [FormSpan],
232    selected: &'a FormSpan,
233) -> Result<Vec<&'a FormSpan>, Error> {
234    let mut result = Vec::new();
235    let mut visited = HashSet::new();
236    let mut next = selected;
237    loop {
238        if !visited.insert(next.range.start) {
239            return Err(invalid("Selected inheritance chain is cyclic"));
240        }
241        result.push(next);
242        let parents = direct_children(spans, next)
243            .filter(|span| span.head.as_deref() == Some("extends"))
244            .collect::<Vec<_>>();
245        match parents.as_slice() {
246            [] => return Ok(result),
247            [parent] => {
248                let name = header_scalar(source, parent, 0)?.0;
249                next = unique_symbol(source, spans, &name)?;
250            }
251            _ => return Err(invalid("Selected symbol has ambiguous inheritance")),
252        }
253    }
254}
255
256fn owned_unit<'a>(owner: &str, child: &'a str) -> Option<(&'a str, u32, &'a str)> {
257    let mut parts = child.rsplitn(3, '_');
258    let style = parts.next()?;
259    let unit = parts.next()?;
260    let prefix = parts.next()?;
261    if prefix.replace("{slash}", "/") != owner {
262        return None;
263    }
264    if unit.is_empty()
265        || style.is_empty()
266        || !unit.bytes().all(|byte| byte.is_ascii_digit())
267        || !style.bytes().all(|byte| byte.is_ascii_digit())
268    {
269        return None;
270    }
271    Some((prefix, unit.parse().ok()?, style))
272}
273
274fn header_scalar(
275    source: &str,
276    span: &FormSpan,
277    index: usize,
278) -> Result<(String, std::ops::Range<usize>), Error> {
279    let mut lexer = Lexer::new(span.text(source)?);
280    lexer.next().transpose()?;
281    lexer.next().transpose()?;
282    let mut token = lexer
283        .next()
284        .transpose()?
285        .ok_or_else(|| invalid("Source form has no scalar"))?;
286    if span.head.as_deref() == Some("property")
287        && token.kind == TokenKind::Atom
288        && token.lexeme == "private"
289    {
290        token = lexer
291            .next()
292            .transpose()?
293            .ok_or_else(|| invalid("Private Source property has no name"))?;
294    }
295    for _ in 0..index {
296        token = lexer
297            .next()
298            .transpose()?
299            .ok_or_else(|| invalid("Source form has no requested scalar"))?;
300    }
301    let value = token_scalar(&token)?;
302    let start = span.range.start + token.position.offset;
303    Ok((value, start..start + token.lexeme.len()))
304}
305
306fn token_scalar(token: &Token<'_>) -> Result<String, Error> {
307    match token.kind {
308        TokenKind::QuotedString => Ok(decode_quoted(token.lexeme)),
309        TokenKind::Atom => Ok(token.lexeme.into()),
310        _ => Err(invalid("Expected a Source string scalar")),
311    }
312}
313
314fn authored_properties(
315    properties: Vec<AuthoredSymbolProperty>,
316    limits: SymbolAuthoringLimits,
317) -> Result<String, Error> {
318    let mut symbol = AuthoredSymbol::new("source-property-insertion");
319    symbol.properties = properties;
320    let mut envelope = AuthoredSymbolLibrary::default();
321    envelope.symbols.push(symbol);
322    let emitted = envelope.canonical_text(limits)?;
323    let (_, spans) = root_and_spans(&emitted, &["kicad_symbol_lib"])?;
324    let mut text = String::new();
325    for span in spans
326        .iter()
327        .filter(|span| span.depth == 2 && span.head.as_deref() == Some("property"))
328    {
329        text.push('\n');
330        text.push_str(span.text(&emitted)?);
331        text.push('\n');
332    }
333    Ok(text)
334}