1use crate::{
2 KiCadNetlist, KiCadNetlistJsonMetadata, PcbView, ProjectDocument, ProjectView,
3 SchematicBundleIndex, SourceBundle, SourceBundleError, SourceBundleErrorKind,
4 build_compiled_schematic_graph, build_kicad_netlist, build_kicad_netlist_json,
5};
6use kicad_monkey_contracts::generated::compiled_schematic_graph::CompiledSchematicGraphA0;
7use serde_json::{Value, json};
8use std::collections::BTreeMap;
9use std::fmt;
10use std::io::{self, Write};
11
12mod components;
13mod hierarchy;
14mod indexes;
15mod pnp;
16mod resource;
17mod schematic_instances;
18mod variants;
19
20pub use schematic_instances::KiCadSchematicInstance;
21
22pub const KICAD_DESIGN_JSON_SCHEMA: &str = "kicad_monkey.design.a0";
23pub const KICAD_DESIGN_JSON_GENERATOR: &str = "kicad_monkey";
24
25#[derive(Debug)]
26pub struct KiCadDesignFacts<'index> {
27 index: &'index SchematicBundleIndex,
28 project: Option<ProjectDocument>,
29 graph: CompiledSchematicGraphA0,
30 netlist: KiCadNetlist,
31}
32
33#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
34pub struct KiCadDesignFactsBuildProfile {
35 pub project_parse_ns: u64,
36 pub compiled_graph_ns: u64,
37 pub netlist_ns: u64,
38}
39
40impl KiCadDesignFacts<'_> {
41 pub fn project(&self) -> Option<ProjectView<'_>> {
42 self.project.as_ref().map(ProjectDocument::view)
43 }
44
45 pub fn graph(&self) -> &CompiledSchematicGraphA0 {
46 &self.graph
47 }
48
49 pub fn netlist(&self) -> &KiCadNetlist {
50 &self.netlist
51 }
52
53 pub fn into_parts(self) -> (CompiledSchematicGraphA0, KiCadNetlist) {
54 (self.graph, self.netlist)
55 }
56
57 pub fn schematic_instances(&self) -> Result<Vec<KiCadSchematicInstance>, KiCadDesignJsonError> {
58 schematic_instances::schematic_instances(self)
59 }
60}
61
62pub fn build_kicad_design_facts<'index>(
63 index: &'index SchematicBundleIndex,
64 bundle: &SourceBundle,
65) -> Result<KiCadDesignFacts<'index>, SourceBundleError> {
66 build_kicad_design_facts_internal(index, bundle, false).map(|(facts, _profile)| facts)
67}
68
69pub fn build_kicad_design_facts_profiled<'index>(
70 index: &'index SchematicBundleIndex,
71 bundle: &SourceBundle,
72) -> Result<(KiCadDesignFacts<'index>, KiCadDesignFactsBuildProfile), SourceBundleError> {
73 build_kicad_design_facts_internal(index, bundle, true)
74}
75
76fn build_kicad_design_facts_internal<'index>(
77 index: &'index SchematicBundleIndex,
78 bundle: &SourceBundle,
79 profile: bool,
80) -> Result<(KiCadDesignFacts<'index>, KiCadDesignFactsBuildProfile), SourceBundleError> {
81 if !index.bundle_belongs_to(bundle) {
82 return Err(SourceBundleError::new(
83 SourceBundleErrorKind::Contract,
84 None,
85 "project source does not belong to the schematic index",
86 ));
87 }
88 let project_started = profile.then(std::time::Instant::now);
89 let project = bundle
90 .project()
91 .map(|source| ProjectDocument::from_reader(source.bytes()))
92 .transpose()
93 .map_err(|error| {
94 SourceBundleError::new(
95 SourceBundleErrorKind::Project,
96 bundle.project_path(),
97 format!("project document is invalid: {error}"),
98 )
99 })?;
100 let project_parse_ns = elapsed_ns(project_started);
101 let project_view = project.as_ref().map(ProjectDocument::view);
102 let graph_started = profile.then(std::time::Instant::now);
103 let graph = build_compiled_schematic_graph(index)?;
104 let compiled_graph_ns = elapsed_ns(graph_started);
105 let netlist_started = profile.then(std::time::Instant::now);
106 let netlist = build_kicad_netlist(index, project_view)?;
107 let netlist_ns = elapsed_ns(netlist_started);
108 Ok((
109 KiCadDesignFacts {
110 index,
111 project,
112 graph,
113 netlist,
114 },
115 KiCadDesignFactsBuildProfile {
116 project_parse_ns,
117 compiled_graph_ns,
118 netlist_ns,
119 },
120 ))
121}
122
123#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
124pub struct KiCadDesignJsonBuildProfile {
125 pub binding_and_preflight_ns: u64,
126 pub netlist_json_ns: u64,
127 pub project_variants_options_ns: u64,
128 pub sheets_ns: u64,
129 pub components_ns: u64,
130 pub hierarchy_and_nets_ns: u64,
131 pub compiled_graph_value_ns: u64,
132 pub pnp_ns: u64,
133 pub classes_and_indexes_ns: u64,
134 pub output_limit_serialization_ns: u64,
135}
136
137#[derive(Clone, Debug, Eq, PartialEq)]
138pub struct KiCadDesignSourcePath {
139 pub filename: String,
140 pub path: String,
141}
142
143#[derive(Clone, Debug, Default, Eq, PartialEq)]
144pub struct KiCadDesignJsonPaths {
145 pub project_name: Option<String>,
146 pub project_filename: Option<String>,
147 pub project_path: Option<String>,
148 pub schematic_paths: BTreeMap<String, KiCadDesignSourcePath>,
149}
150
151#[derive(Clone, Copy, Debug)]
152pub struct KiCadDesignPcb<'a> {
153 pub source_filename: &'a str,
154 pub view: &'a PcbView<'a>,
155}
156
157#[derive(Debug)]
158pub struct KiCadDesignJsonError {
159 message: String,
160}
161
162impl KiCadDesignJsonError {
163 fn context(context: &str, error: impl fmt::Display) -> Self {
164 Self {
165 message: format!("{context}: {error}"),
166 }
167 }
168}
169
170impl fmt::Display for KiCadDesignJsonError {
171 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
172 formatter.write_str(&self.message)
173 }
174}
175
176impl std::error::Error for KiCadDesignJsonError {}
177
178fn elapsed_ns(started: Option<std::time::Instant>) -> u64 {
179 started.map_or(0, |started| {
180 u64::try_from(started.elapsed().as_nanos()).unwrap_or(u64::MAX)
181 })
182}
183
184impl From<SourceBundleError> for KiCadDesignJsonError {
185 fn from(error: SourceBundleError) -> Self {
186 Self::context("could not resolve design variant", error)
187 }
188}
189
190pub fn build_kicad_design_json(
191 index: &SchematicBundleIndex,
192 facts: &KiCadDesignFacts<'_>,
193 paths: &KiCadDesignJsonPaths,
194 pcb: Option<KiCadDesignPcb<'_>>,
195 include_indexes: bool,
196) -> Result<Value, KiCadDesignJsonError> {
197 build_kicad_design_json_internal(index, facts, paths, pcb, include_indexes, false)
198 .map(|(value, _profile)| value)
199}
200
201pub fn build_kicad_design_json_profiled(
202 index: &SchematicBundleIndex,
203 facts: &KiCadDesignFacts<'_>,
204 paths: &KiCadDesignJsonPaths,
205 pcb: Option<KiCadDesignPcb<'_>>,
206 include_indexes: bool,
207) -> Result<(Value, KiCadDesignJsonBuildProfile), KiCadDesignJsonError> {
208 build_kicad_design_json_internal(index, facts, paths, pcb, include_indexes, true)
209}
210
211#[allow(
212 clippy::too_many_lines,
213 reason = "the profiled builder preserves one ordered Design JSON assembly flow"
214)]
215fn build_kicad_design_json_internal(
216 index: &SchematicBundleIndex,
217 facts: &KiCadDesignFacts<'_>,
218 paths: &KiCadDesignJsonPaths,
219 pcb: Option<KiCadDesignPcb<'_>>,
220 include_indexes: bool,
221 profile: bool,
222) -> Result<(Value, KiCadDesignJsonBuildProfile), KiCadDesignJsonError> {
223 let preflight_started = profile.then(std::time::Instant::now);
224 validate_facts_binding(index, facts)?;
225 let project = facts.project();
226 let graph = facts.graph();
227 let netlist = facts.netlist();
228 resource::preflight_design_json(index, project, netlist, graph, paths, pcb, include_indexes)?;
229 let binding_and_preflight_ns = elapsed_ns(preflight_started);
230 let netlist_json_started = profile.then(std::time::Instant::now);
231 let netlist_json = build_kicad_netlist_json(netlist, KiCadNetlistJsonMetadata::default());
232 let netlist_json_ns = elapsed_ns(netlist_json_started);
233 let mut result = serde_json::Map::new();
234 result.insert("schema".to_owned(), json!(KICAD_DESIGN_JSON_SCHEMA));
235 result.insert("generator".to_owned(), json!(KICAD_DESIGN_JSON_GENERATOR));
236 let project_started = profile.then(std::time::Instant::now);
237 result.insert("project".to_owned(), project_json(project, paths)?);
238 result.insert(
239 "variants".to_owned(),
240 variants::variants_json(index, project)?,
241 );
242 result.insert("options".to_owned(), options_json(project));
243 let project_variants_options_ns = elapsed_ns(project_started);
244 let sheets_started = profile.then(std::time::Instant::now);
245 result.insert(
246 "sheets".to_owned(),
247 hierarchy::sheets_json(index, netlist, paths),
248 );
249 let sheets_ns = elapsed_ns(sheets_started);
250 let components_started = profile.then(std::time::Instant::now);
251 result.insert(
252 "components".to_owned(),
253 components::components_json(netlist, &netlist_json),
254 );
255 let components_ns = elapsed_ns(components_started);
256 let hierarchy_started = profile.then(std::time::Instant::now);
257 result.insert(
258 "schematic_hierarchy".to_owned(),
259 hierarchy::schematic_hierarchy_json(index, paths),
260 );
261 result.insert("nets".to_owned(), netlist_json["nets"].clone());
262 let hierarchy_and_nets_ns = elapsed_ns(hierarchy_started);
263 let graph_started = profile.then(std::time::Instant::now);
264 result.insert(
265 "compiled_schematic_graph".to_owned(),
266 serde_json::to_value(graph)
267 .map_err(|error| KiCadDesignJsonError::context("could not encode graph", error))?,
268 );
269 let compiled_graph_value_ns = elapsed_ns(graph_started);
270 let pnp_started = profile.then(std::time::Instant::now);
271 if let Some(pcb) = pcb
272 && let Some(payload) = pnp::pnp_json(pcb, netlist, &netlist_json)?
273 {
274 result.insert("pnp".to_owned(), payload);
275 }
276 let pnp_ns = elapsed_ns(pnp_started);
277 let indexes_started = profile.then(std::time::Instant::now);
278 if !netlist.net_classes.is_empty() {
279 result.insert(
280 "net_classes".to_owned(),
281 netlist_json["net_classes"].clone(),
282 );
283 result.insert(
284 "net_name_to_classes".to_owned(),
285 indexes::net_name_to_classes(netlist),
286 );
287 }
288 if include_indexes {
289 result.insert("indexes".to_owned(), indexes::indexes_json(netlist));
290 }
291 let classes_and_indexes_ns = elapsed_ns(indexes_started);
292 let result = Value::Object(result);
293 let output_limit_started = profile.then(std::time::Instant::now);
294 enforce_output_limit(&result, usize::MAX)?;
295 let output_limit_serialization_ns = elapsed_ns(output_limit_started);
296 Ok((
297 result,
298 KiCadDesignJsonBuildProfile {
299 binding_and_preflight_ns,
300 netlist_json_ns,
301 project_variants_options_ns,
302 sheets_ns,
303 components_ns,
304 hierarchy_and_nets_ns,
305 compiled_graph_value_ns,
306 pnp_ns,
307 classes_and_indexes_ns,
308 output_limit_serialization_ns,
309 },
310 ))
311}
312
313fn validate_facts_binding(
314 index: &SchematicBundleIndex,
315 bound: &KiCadDesignFacts<'_>,
316) -> Result<(), KiCadDesignJsonError> {
317 if !std::ptr::eq(index, bound.index) {
318 return Err(KiCadDesignJsonError::context(
319 "compiled schematic graph does not belong to the supplied bundle",
320 "graph was built from a different schematic index",
321 ));
322 }
323 Ok(())
324}
325
326fn enforce_output_limit(
327 value: &Value,
328 max_output_bytes: usize,
329) -> Result<(), KiCadDesignJsonError> {
330 let mut writer = LimitedWriter::new(max_output_bytes);
331 serde_json::to_writer(&mut writer, value).map_err(|error| {
332 KiCadDesignJsonError::context("KiCad design JSON output limit exceeded", error)
333 })
334}
335
336struct LimitedWriter {
337 written: usize,
338 limit: usize,
339}
340
341impl LimitedWriter {
342 const fn new(limit: usize) -> Self {
343 Self { written: 0, limit }
344 }
345}
346
347impl Write for LimitedWriter {
348 fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
349 let next = self
350 .written
351 .checked_add(buffer.len())
352 .filter(|next| *next <= self.limit)
353 .ok_or_else(|| io::Error::other(format!("output exceeds {} bytes", self.limit)))?;
354 self.written = next;
355 Ok(buffer.len())
356 }
357
358 fn flush(&mut self) -> io::Result<()> {
359 Ok(())
360 }
361}
362
363fn project_json(
364 project: Option<ProjectView<'_>>,
365 paths: &KiCadDesignJsonPaths,
366) -> Result<Value, KiCadDesignJsonError> {
367 let variables = project
368 .map(|view| view.text_variables())
369 .transpose()
370 .map_err(|error| KiCadDesignJsonError::context("could not read text variables", error))?
371 .unwrap_or_default()
372 .into_iter()
373 .collect::<BTreeMap<_, _>>();
374 Ok(json!({
375 "name": paths.project_name,
376 "filename": paths.project_filename,
377 "path": paths.project_path,
378 "text_variables": variables,
379 }))
380}
381
382fn options_json(project: Option<ProjectView<'_>>) -> Value {
383 let first_id = project.and_then(|view| view.get_path("schematic.subpart_first_id"));
384 let separator = project.and_then(|view| view.get_path("schematic.subpart_id_separator"));
385 json!({
386 "net_identifier_scope": "KICAD_PROJECT",
387 "allow_ports_to_name_nets": true,
388 "allow_sheet_entries_to_name_nets": true,
389 "allow_single_pin_nets": true,
390 "append_sheet_numbers_to_local_nets": false,
391 "power_port_names_take_priority": true,
392 "higher_level_names_take_priority": true,
393 "auto_sheet_numbering": true,
394 "kicad_schematic_format": "sexpr",
395 "kicad_supported_oracle_versions": ["9", "10"],
396 "kicad_subpart_first_id": first_id,
397 "kicad_subpart_id_separator": separator,
398 })
399}
400
401#[cfg(test)]
402mod tests {
403 use super::{LimitedWriter, enforce_output_limit};
404 use serde_json::json;
405 use std::io::Write;
406
407 #[test]
408 fn output_limit_accepts_exact_and_rejects_one_under() {
409 let value = json!({"items": [1, 2, 3]});
410 let encoded = serde_json::to_vec(&value).unwrap();
411 enforce_output_limit(&value, encoded.len()).expect("exact output limit");
412 let error = enforce_output_limit(&value, encoded.len() - 1).expect_err("one byte over");
413 assert!(error.to_string().contains("output exceeds"));
414 }
415
416 #[test]
417 fn limited_writer_rejects_counter_overflow() {
418 let mut writer = LimitedWriter {
419 written: usize::MAX,
420 limit: usize::MAX,
421 };
422 assert!(writer.write(&[0]).is_err());
423 }
424}