1use crate::sexpr::{Lexer, TokenKind, decode_quoted};
4use crate::sexpr_projection::{FormSpan, Selector, scan_form_spans};
5use crate::{SourceBundleError, SourceBundleErrorKind};
6use std::ops::Range;
7
8#[derive(Clone, Debug, Eq, PartialEq)]
10pub struct KiCadVariantField {
11 pub name: String,
12 pub value: String,
13 pub value_declared: bool,
14 pub source_range: Range<usize>,
15}
16
17#[derive(Clone, Debug, Default, Eq, PartialEq)]
19pub struct KiCadVariantFlags {
20 pub dnp: Option<bool>,
21 pub exclude_from_sim: Option<bool>,
22 pub in_bom: Option<bool>,
23 pub on_board: Option<bool>,
24 pub in_pos_files: Option<bool>,
25 pub exclude_from_bom: Option<bool>,
26 pub exclude_from_pos_files: Option<bool>,
27}
28
29#[derive(Clone, Debug, Eq, PartialEq)]
31pub struct KiCadAuthoredVariant {
32 pub name: String,
33 pub flags: KiCadVariantFlags,
34 pub fields: Vec<KiCadVariantField>,
35 pub unsupported_tokens: Vec<String>,
36 pub source_range: Range<usize>,
37}
38
39#[derive(Clone, Debug, Eq, PartialEq)]
41pub struct KiCadVariantInstance {
42 pub project: String,
43 pub path: String,
44 pub page: Option<String>,
45 pub variants: Vec<KiCadAuthoredVariant>,
46 pub source_range: Range<usize>,
47}
48
49pub(crate) fn error(path: &str, message: impl Into<String>) -> SourceBundleError {
50 SourceBundleError::new(SourceBundleErrorKind::Schematic, Some(path), message)
51}
52
53pub(crate) fn children(
54 source: &str,
55 parent: Option<&FormSpan>,
56 path: &str,
57) -> Result<Vec<FormSpan>, SourceBundleError> {
58 let (text, offset) = parent.map_or(Ok((source, 0)), |span| {
59 span.text(source)
60 .map(|text| (text, span.range.start))
61 .map_err(|fault| error(path, fault.to_string()))
62 })?;
63 let mut spans = scan_form_spans(
64 text,
65 &Selector {
66 min_depth: Some(1),
67 max_depth: Some(1),
68 ..Selector::default()
69 },
70 )
71 .map_err(|fault| error(path, fault.to_string()))?;
72 for span in &mut spans {
73 span.range.start += offset;
74 span.range.end += offset;
75 }
76 Ok(spans)
77}
78
79pub(crate) fn scalars(
80 source: &str,
81 span: &FormSpan,
82 path: &str,
83) -> Result<Vec<String>, SourceBundleError> {
84 let text = span
85 .text(source)
86 .map_err(|fault| error(path, fault.to_string()))?;
87 let mut depth = 0usize;
88 let mut head_seen = false;
89 let mut output = Vec::new();
90 let mut retained = 0usize;
91 for token in Lexer::new(text) {
92 let token = token.map_err(|fault| error(path, fault.to_string()))?;
93 match token.kind {
94 TokenKind::Left => depth += 1,
95 TokenKind::Right => depth = depth.saturating_sub(1),
96 _ if depth == 1 && !head_seen => head_seen = true,
97 _ if depth == 1 => {
98 let value = if token.kind == TokenKind::QuotedString {
99 decode_quoted(token.lexeme)
100 } else {
101 token.lexeme.to_owned()
102 };
103 retained = retained
104 .checked_add(value.len())
105 .ok_or_else(|| error(path, "variant scalar bytes exceed their limit"))?;
106 output.push(value);
107 }
108 _ => {}
109 }
110 }
111 Ok(output)
112}
113
114pub(crate) fn child_value(
115 source: &str,
116 forms: &[FormSpan],
117 name: &str,
118 path: &str,
119) -> Result<Option<String>, SourceBundleError> {
120 forms
121 .iter()
122 .rev()
123 .find(|span| span.head.as_deref() == Some(name))
124 .map(|span| {
125 let values = scalars(source, span, path)?;
126 match values.as_slice() {
127 [value] => Ok(value.clone()),
128 _ => Err(error(
129 path,
130 format!("variant {name} requires exactly one scalar"),
131 )),
132 }
133 })
134 .transpose()
135}
136
137pub(crate) fn parse_variant(
138 source: &str,
139 span: &FormSpan,
140 path: &str,
141 pcb: bool,
142) -> Result<KiCadAuthoredVariant, SourceBundleError> {
143 let forms = children(source, Some(span), path)?;
144 let mut variant = KiCadAuthoredVariant {
145 name: child_value(source, &forms, "name", path)?.unwrap_or_default(),
146 flags: KiCadVariantFlags::default(),
147 fields: Vec::new(),
148 unsupported_tokens: Vec::new(),
149 source_range: span.range.clone(),
150 };
151 for form in &forms {
152 let head = form.head.as_deref().unwrap_or("");
153 if head == "name" {
154 continue;
155 }
156 if head == "field" {
157 let values = children(source, Some(form), path)?;
158 let name = child_value(source, &values, "name", path)?.unwrap_or_default();
159 let value = child_value(source, &values, "value", path)?;
160 if !name.is_empty() {
161 variant.fields.push(KiCadVariantField {
162 name,
163 value_declared: value.is_some(),
164 value: value.unwrap_or_default(),
165 source_range: form.range.clone(),
166 });
167 }
168 for field in &values {
169 if !matches!(field.head.as_deref(), Some("name" | "value")) {
170 variant
171 .unsupported_tokens
172 .push(format!("field.{}", field.head.as_deref().unwrap_or("")));
173 }
174 }
175 continue;
176 }
177 let slot = match (pcb, head) {
178 (_, "dnp") => Some(&mut variant.flags.dnp),
179 (false, "exclude_from_sim") => Some(&mut variant.flags.exclude_from_sim),
180 (false, "in_bom") => Some(&mut variant.flags.in_bom),
181 (false, "on_board") => Some(&mut variant.flags.on_board),
182 (false, "in_pos_files") => Some(&mut variant.flags.in_pos_files),
183 (true, "exclude_from_bom") => Some(&mut variant.flags.exclude_from_bom),
184 (true, "exclude_from_pos_files") => Some(&mut variant.flags.exclude_from_pos_files),
185 _ => None,
186 };
187 if let Some(slot) = slot {
188 let values = scalars(source, form, path)?;
189 *slot = Some(match values.as_slice() {
190 [] if pcb => true,
191 [value] if value == "yes" => true,
192 [value] if value == "no" => false,
193 _ => {
194 return Err(error(
195 path,
196 format!(
197 "variant {head} requires yes/no{}",
198 if pcb { " or an empty true form" } else { "" }
199 ),
200 ));
201 }
202 });
203 } else {
204 variant.unsupported_tokens.push(head.to_owned());
205 }
206 }
207 Ok(variant)
208}
209
210pub(crate) fn instances(
211 source: &str,
212 span: &FormSpan,
213 path: &str,
214) -> Result<Vec<KiCadVariantInstance>, SourceBundleError> {
215 let mut output = Vec::new();
216 for project in children(source, Some(span), path)? {
217 if project.head.as_deref() != Some("project") {
218 return Err(error(path, "instance requires a project clause"));
219 }
220 let name = scalars(source, &project, path)?
221 .first()
222 .cloned()
223 .unwrap_or_default();
224 for instance in children(source, Some(&project), path)? {
225 if instance.head.as_deref() != Some("path") {
226 return Err(error(path, "project instance requires a path clause"));
227 }
228 let forms = children(source, Some(&instance), path)?;
229 let mut variants = Vec::new();
230 for variant in forms
231 .iter()
232 .filter(|form| form.head.as_deref() == Some("variant"))
233 {
234 variants.push(parse_variant(source, variant, path, false)?);
235 }
236 output.push(KiCadVariantInstance {
237 project: name.clone(),
238 path: scalars(source, &instance, path)?
239 .first()
240 .cloned()
241 .unwrap_or_default(),
242 page: child_value(source, &forms, "page", path)?,
243 variants,
244 source_range: instance.range,
245 });
246 }
247 }
248 Ok(output)
249}