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

kicad_monkey_codegen/
main.rs

1//! Deterministic Rust projection from TypeSpec-generated JSON Schemas.
2
3use anyhow::{Context, Result, bail};
4use schemars::schema::RootSchema;
5use serde_json::Value;
6use std::collections::{BTreeMap, BTreeSet};
7use std::env;
8use std::fs;
9use std::io::Write;
10use std::path::PathBuf;
11use std::process::{Command, Stdio};
12use typify::{TypeSpace, TypeSpaceSettings};
13
14mod config_projection;
15mod text_contract;
16
17const SCHEMAS: [(&str, &str); 30] = [
18    ("BoardPlotDocument.json", "board_plot_document.rs"),
19    ("BoardPlotRequest.json", "board_plot_request.rs"),
20    ("BoardPlotResult.json", "board_plot_result.rs"),
21    ("BuildRequest.json", "build_request.rs"),
22    ("BuildResult.json", "build_result.rs"),
23    ("ScanRequest.json", "scan_request.rs"),
24    ("ScanResult.json", "scan_result.rs"),
25    ("FootprintEditRequest.json", "footprint_edit_request.rs"),
26    ("FootprintEditResult.json", "footprint_edit_result.rs"),
27    ("FootprintReadRequest.json", "footprint_read_request.rs"),
28    ("FootprintReadResult.json", "footprint_read_result.rs"),
29    ("FootprintPlotDocument.json", "footprint_plot_document.rs"),
30    ("FootprintPlotRequest.json", "footprint_plot_request.rs"),
31    ("FootprintPlotResult.json", "footprint_plot_result.rs"),
32    ("SymbolPlotDocument.json", "symbol_plot_document.rs"),
33    ("SymbolPlotRequest.json", "symbol_plot_request.rs"),
34    ("SymbolPlotResult.json", "symbol_plot_result.rs"),
35    ("SchematicPlotDocument.json", "schematic_plot_document.rs"),
36    ("SchematicPlotRequest.json", "schematic_plot_request.rs"),
37    ("SchematicPlotResult.json", "schematic_plot_result.rs"),
38    (
39        "SymbolLibraryEditRequest.json",
40        "symbol_library_edit_request.rs",
41    ),
42    (
43        "SymbolLibraryEditResult.json",
44        "symbol_library_edit_result.rs",
45    ),
46    (
47        "SymbolLibraryReadRequest.json",
48        "symbol_library_read_request.rs",
49    ),
50    (
51        "SymbolLibraryReadResult.json",
52        "symbol_library_read_result.rs",
53    ),
54    ("CompiledSchematicGraph.json", "compiled_schematic_graph.rs"),
55    ("SourceBundleManifest.json", "source_bundle_manifest.rs"),
56    ("FontBundleManifest.json", "font_bundle_manifest.rs"),
57    ("FontResolutionRequest.json", "font_resolution_request.rs"),
58    ("ShapingRecord.json", "shaping_record.rs"),
59    ("OutlineVector.json", "outline_vector.rs"),
60];
61
62const PLOTTER_OPERATION_KINDS: [(&str, &str, &str); 14] = [
63    (
64        "ThickSegmentOperation",
65        "ThickSegment",
66        "deserialize_thick_segment_kind",
67    ),
68    (
69        "ArcThreePointOperation",
70        "ArcThreePoint",
71        "deserialize_arc_three_point_kind",
72    ),
73    ("CircleOperation", "Circle", "deserialize_circle_kind"),
74    ("RectOperation", "Rect", "deserialize_rect_kind"),
75    (
76        "PlotPolyOperation",
77        "PlotPoly",
78        "deserialize_plot_poly_kind",
79    ),
80    (
81        "BezierCurveOperation",
82        "BezierCurve",
83        "deserialize_bezier_curve_kind",
84    ),
85    ("TextOperation", "Text", "deserialize_text_kind"),
86    (
87        "PlotImageOperation",
88        "PlotImage",
89        "deserialize_plot_image_kind",
90    ),
91    (
92        "FlashPadCircleOperation",
93        "FlashPadCircle",
94        "deserialize_flash_pad_circle_kind",
95    ),
96    (
97        "FlashPadOvalOperation",
98        "FlashPadOval",
99        "deserialize_flash_pad_oval_kind",
100    ),
101    (
102        "FlashPadRectOperation",
103        "FlashPadRect",
104        "deserialize_flash_pad_rect_kind",
105    ),
106    (
107        "FlashPadRoundRectOperation",
108        "FlashPadRoundRect",
109        "deserialize_flash_pad_round_rect_kind",
110    ),
111    (
112        "FlashPadCustomOperation",
113        "FlashPadCustom",
114        "deserialize_flash_pad_custom_kind",
115    ),
116    (
117        "FlashPadTrapezOperation",
118        "FlashPadTrapez",
119        "deserialize_flash_pad_trapez_kind",
120    ),
121];
122
123const BOARD_FOOTPRINT_OPERATION_KINDS: [(&str, &str, &str); 15] = [
124    (
125        "BoardFootprintThickSegmentOperation",
126        "ThickSegment",
127        "deserialize_thick_segment_kind",
128    ),
129    (
130        "BoardFootprintArcThreePointOperation",
131        "ArcThreePoint",
132        "deserialize_arc_three_point_kind",
133    ),
134    (
135        "BoardFootprintCircleOperation",
136        "Circle",
137        "deserialize_circle_kind",
138    ),
139    (
140        "BoardFootprintRectOperation",
141        "Rect",
142        "deserialize_rect_kind",
143    ),
144    (
145        "BoardFootprintPlotPolyOperation",
146        "PlotPoly",
147        "deserialize_plot_poly_kind",
148    ),
149    (
150        "BoardFootprintBezierCurveOperation",
151        "BezierCurve",
152        "deserialize_bezier_curve_kind",
153    ),
154    (
155        "BoardFootprintTextOperation",
156        "Text",
157        "deserialize_text_kind",
158    ),
159    (
160        "BoardFootprintFlashPadCircleOperation",
161        "FlashPadCircle",
162        "deserialize_flash_pad_circle_kind",
163    ),
164    (
165        "BoardFootprintFlashPadOvalOperation",
166        "FlashPadOval",
167        "deserialize_flash_pad_oval_kind",
168    ),
169    (
170        "BoardFootprintFlashPadRectOperation",
171        "FlashPadRect",
172        "deserialize_flash_pad_rect_kind",
173    ),
174    (
175        "BoardFootprintFlashPadRoundRectOperation",
176        "FlashPadRoundRect",
177        "deserialize_flash_pad_round_rect_kind",
178    ),
179    (
180        "BoardFootprintFlashPadCustomOperation",
181        "FlashPadCustom",
182        "deserialize_flash_pad_custom_kind",
183    ),
184    (
185        "BoardFootprintFlashPadTrapezOperation",
186        "FlashPadTrapez",
187        "deserialize_flash_pad_trapez_kind",
188    ),
189    (
190        "BoardFootprintStartBlockOperation",
191        "StartBlock",
192        "deserialize_start_block_kind",
193    ),
194    (
195        "BoardFootprintEndBlockOperation",
196        "EndBlock",
197        "deserialize_end_block_kind",
198    ),
199];
200
201const SCHEMATIC_RECORD_KINDS: [(&str, &str, &str); 23] = [
202    (
203        "SchematicSheetHeaderPlotRecord",
204        "sheet_header",
205        "deserialize_sheet_header_kind",
206    ),
207    (
208        "SchematicWirePlotRecord",
209        "wire",
210        "deserialize_wire_record_kind",
211    ),
212    (
213        "SchematicBusPlotRecord",
214        "bus",
215        "deserialize_bus_record_kind",
216    ),
217    (
218        "SchematicBusEntryPlotRecord",
219        "bus_entry",
220        "deserialize_bus_entry_record_kind",
221    ),
222    (
223        "SchematicJunctionPlotRecord",
224        "junction",
225        "deserialize_junction_record_kind",
226    ),
227    (
228        "SchematicNoConnectPlotRecord",
229        "no_connect",
230        "deserialize_no_connect_record_kind",
231    ),
232    (
233        "SchematicLabelPlotRecord",
234        "label",
235        "deserialize_label_record_kind",
236    ),
237    (
238        "SchematicGlobalLabelPlotRecord",
239        "global_label",
240        "deserialize_global_label_record_kind",
241    ),
242    (
243        "SchematicHierarchicalLabelPlotRecord",
244        "hierarchical_label",
245        "deserialize_hierarchical_label_record_kind",
246    ),
247    (
248        "SchematicNetclassFlagPlotRecord",
249        "netclass_flag",
250        "deserialize_netclass_flag_record_kind",
251    ),
252    (
253        "SchematicTextPlotRecord",
254        "text",
255        "deserialize_text_record_kind",
256    ),
257    (
258        "SchematicTextBoxPlotRecord",
259        "text_box",
260        "deserialize_text_box_record_kind",
261    ),
262    (
263        "SchematicGraphicPolylinePlotRecord",
264        "graphic_polyline",
265        "deserialize_graphic_polyline_record_kind",
266    ),
267    (
268        "SchematicGraphicArcPlotRecord",
269        "graphic_arc",
270        "deserialize_graphic_arc_record_kind",
271    ),
272    (
273        "SchematicGraphicCirclePlotRecord",
274        "graphic_circle",
275        "deserialize_graphic_circle_record_kind",
276    ),
277    (
278        "SchematicGraphicRectanglePlotRecord",
279        "graphic_rectangle",
280        "deserialize_graphic_rectangle_record_kind",
281    ),
282    (
283        "SchematicGraphicBezierPlotRecord",
284        "graphic_bezier",
285        "deserialize_graphic_bezier_record_kind",
286    ),
287    (
288        "SchematicRuleAreaPlotRecord",
289        "rule_area",
290        "deserialize_rule_area_record_kind",
291    ),
292    (
293        "SchematicImagePlotRecord",
294        "image",
295        "deserialize_image_record_kind",
296    ),
297    (
298        "SchematicTablePlotRecord",
299        "table",
300        "deserialize_table_record_kind",
301    ),
302    (
303        "SchematicSymbolInstancePlotRecord",
304        "symbol_instance",
305        "deserialize_symbol_instance_record_kind",
306    ),
307    (
308        "SchematicSymbolOverplotPlotRecord",
309        "symbol_overplot",
310        "deserialize_symbol_overplot_record_kind",
311    ),
312    (
313        "SchematicSheetPlotRecord",
314        "sheet",
315        "deserialize_sheet_record_kind",
316    ),
317];
318
319const SCHEMATIC_SYMBOL_OPERATION_KINDS: [(&str, &str, &str); 16] = [
320    (
321        "ThickSegmentOperation",
322        "ThickSegment",
323        "deserialize_thick_segment_kind",
324    ),
325    (
326        "ArcThreePointOperation",
327        "ArcThreePoint",
328        "deserialize_arc_three_point_kind",
329    ),
330    ("CircleOperation", "Circle", "deserialize_circle_kind"),
331    ("RectOperation", "Rect", "deserialize_rect_kind"),
332    (
333        "PlotPolyOperation",
334        "PlotPoly",
335        "deserialize_plot_poly_kind",
336    ),
337    (
338        "BezierCurveOperation",
339        "BezierCurve",
340        "deserialize_bezier_curve_kind",
341    ),
342    ("TextOperation", "Text", "deserialize_text_kind"),
343    (
344        "PlotImageOperation",
345        "PlotImage",
346        "deserialize_plot_image_kind",
347    ),
348    (
349        "FlashPadCircleOperation",
350        "FlashPadCircle",
351        "deserialize_flash_pad_circle_kind",
352    ),
353    (
354        "FlashPadOvalOperation",
355        "FlashPadOval",
356        "deserialize_flash_pad_oval_kind",
357    ),
358    (
359        "FlashPadRectOperation",
360        "FlashPadRect",
361        "deserialize_flash_pad_rect_kind",
362    ),
363    (
364        "FlashPadRoundRectOperation",
365        "FlashPadRoundRect",
366        "deserialize_flash_pad_round_rect_kind",
367    ),
368    (
369        "FlashPadCustomOperation",
370        "FlashPadCustom",
371        "deserialize_flash_pad_custom_kind",
372    ),
373    (
374        "FlashPadTrapezOperation",
375        "FlashPadTrapez",
376        "deserialize_flash_pad_trapez_kind",
377    ),
378    (
379        "SchematicSymbolStartBlockOperation",
380        "StartBlock",
381        "deserialize_start_block_kind",
382    ),
383    (
384        "SchematicSymbolEndBlockOperation",
385        "EndBlock",
386        "deserialize_end_block_kind",
387    ),
388];
389
390const SCHEMATIC_SHEET_OPERATION_KINDS: [(&str, &str, &str); 6] = [
391    (
392        "ThickSegmentOperation",
393        "ThickSegment",
394        "deserialize_thick_segment_kind",
395    ),
396    ("RectOperation", "Rect", "deserialize_rect_kind"),
397    (
398        "PlotPolyOperation",
399        "PlotPoly",
400        "deserialize_plot_poly_kind",
401    ),
402    ("TextOperation", "Text", "deserialize_text_kind"),
403    (
404        "SchematicSheetStartBlockOperation",
405        "StartBlock",
406        "deserialize_start_block_kind",
407    ),
408    (
409        "SchematicSheetEndBlockOperation",
410        "EndBlock",
411        "deserialize_end_block_kind",
412    ),
413];
414
415fn main() -> Result<()> {
416    let arguments: Vec<String> = env::args().skip(1).collect();
417    if arguments
418        .first()
419        .is_some_and(|value| value == "--standalone")
420    {
421        return generate_standalone(&arguments[1..]);
422    }
423    let check = env::args().skip(1).any(|argument| argument == "--check");
424    let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../..");
425    let schema_root = root.join("contracts/generated/schema");
426    let output_root = root.join("src/rs/kicad-monkey-contracts/src/generated");
427    let mut expected = BTreeMap::new();
428    let mut modules = Vec::new();
429
430    for (schema_name, output_name) in SCHEMAS {
431        let schema_path = schema_root.join(schema_name);
432        let mut schema: Value = serde_json::from_slice(
433            &fs::read(&schema_path).with_context(|| format!("read {}", schema_path.display()))?,
434        )?;
435        let published_schema = schema.clone();
436        validate_plotter_operation_kinds(schema_name, &schema)?;
437        flatten_board_footprint_operation_extensions(schema_name, &mut schema)?;
438        project_schematic_request_fields(schema_name, &mut schema)?;
439        project_for_typify(&mut schema);
440        promote_disjoint_record_unions(&mut schema);
441        project_tri_state_via_drill_layers(&mut schema);
442        let generated = project_generated_presence(
443            schema_name,
444            &published_schema,
445            generate(schema_name, schema)?,
446        )?;
447        expected.insert(output_root.join(output_name), generated);
448        modules.push(output_name.trim_end_matches(".rs"));
449    }
450    modules.sort_unstable();
451    let module_source = format!(
452        "//! TypeSpec-generated modules. Regenerate; do not edit module contents.\n\n{}\n",
453        modules
454            .into_iter()
455            .map(|module| format!("pub mod {module};"))
456            .collect::<Vec<_>>()
457            .join("\n")
458    );
459    expected.insert(output_root.join("mod.rs"), module_source);
460
461    for (path, content) in expected {
462        if check {
463            let current = fs::read_to_string(&path)
464                .with_context(|| format!("missing generated Rust file {}", path.display()))?;
465            if current != content {
466                bail!("stale generated Rust file {}", path.display());
467            }
468        } else {
469            fs::write(&path, content).with_context(|| format!("write {}", path.display()))?;
470        }
471    }
472    Ok(())
473}
474
475/// Generate a downstream-owned contract without modifying Monkey's catalog.
476fn generate_standalone(arguments: &[String]) -> Result<()> {
477    if !(arguments.len() == 2 || (arguments.len() == 3 && arguments[2] == "--check")) {
478        bail!("usage: kicad-monkey-codegen --standalone SCHEMA OUTPUT [--check]");
479    }
480    let schema_path = PathBuf::from(&arguments[0]);
481    let output = PathBuf::from(&arguments[1]);
482    let mut schema: Value = serde_json::from_slice(&fs::read(&schema_path)?)?;
483    let published = schema.clone();
484    project_for_typify(&mut schema);
485    let generated = config_projection::preserve_config_presence(
486        &published,
487        generate("Cruncher PCB SVG config", schema)?,
488    )?;
489    if arguments.len() == 3 {
490        if fs::read_to_string(&output)? != generated {
491            bail!("stale generated Rust file {}", output.display());
492        }
493    } else {
494        if let Some(parent) = output.parent() {
495            fs::create_dir_all(parent)?;
496        }
497        fs::write(output, generated)?;
498    }
499    Ok(())
500}
501
502fn flatten_board_footprint_operation_extensions(
503    schema_name: &str,
504    schema: &mut Value,
505) -> Result<()> {
506    if schema_name != "BoardPlotDocument.json" {
507        return Ok(());
508    }
509    for (structure, _, _) in BOARD_FOOTPRINT_OPERATION_KINDS.iter().take(13) {
510        if schema
511            .pointer(&format!("/$defs/{structure}/allOf"))
512            .is_none()
513        {
514            continue;
515        }
516        let base_reference = schema
517            .pointer(&format!("/$defs/{structure}/allOf/0/$ref"))
518            .and_then(Value::as_str)
519            .with_context(|| format!("missing generated {structure} base reference"))?;
520        let base = base_reference
521            .strip_prefix("#/$defs/")
522            .with_context(|| format!("{structure} base reference leaves $defs"))?;
523        let base_properties = schema
524            .pointer(&format!("/$defs/{base}/properties"))
525            .and_then(Value::as_object)
526            .with_context(|| format!("missing generated {base} properties"))?
527            .clone();
528        let base_required = schema.pointer(&format!("/$defs/{base}/required")).cloned();
529        let extension = schema
530            .pointer_mut(&format!("/$defs/{structure}"))
531            .and_then(Value::as_object_mut)
532            .with_context(|| format!("missing generated {structure}"))?;
533        extension.remove("allOf");
534        let properties = extension
535            .get_mut("properties")
536            .and_then(Value::as_object_mut)
537            .with_context(|| format!("missing generated {structure} properties"))?;
538        for (name, property) in base_properties {
539            if properties.insert(name.clone(), property).is_some() {
540                bail!("{structure} unexpectedly redeclared base property {name}");
541            }
542        }
543        if let Some(required) = base_required {
544            extension.insert("required".to_owned(), required);
545        }
546    }
547    Ok(())
548}
549
550fn validate_plotter_operation_kinds(schema_name: &str, schema: &Value) -> Result<()> {
551    if !matches!(
552        schema_name,
553        "BoardPlotDocument.json"
554            | "FootprintPlotDocument.json"
555            | "SchematicPlotDocument.json"
556            | "SymbolPlotDocument.json"
557    ) {
558        return Ok(());
559    }
560    validate_operation_union(
561        schema_name,
562        schema,
563        "PlotterOperation",
564        &PLOTTER_OPERATION_KINDS,
565    )?;
566    if schema_name == "BoardPlotDocument.json" {
567        validate_operation_union(
568            schema_name,
569            schema,
570            "BoardFootprintOperation",
571            &BOARD_FOOTPRINT_OPERATION_KINDS,
572        )?;
573    }
574    if schema_name == "SchematicPlotDocument.json" {
575        validate_operation_union(
576            schema_name,
577            schema,
578            "SchematicPlotRecord",
579            &SCHEMATIC_RECORD_KINDS,
580        )?;
581        validate_operation_union(
582            schema_name,
583            schema,
584            "SchematicSymbolOperation",
585            &SCHEMATIC_SYMBOL_OPERATION_KINDS,
586        )?;
587        validate_operation_union(
588            schema_name,
589            schema,
590            "SchematicSheetOperation",
591            &SCHEMATIC_SHEET_OPERATION_KINDS,
592        )?;
593    }
594    Ok(())
595}
596
597fn validate_operation_union(
598    schema_name: &str,
599    schema: &Value,
600    union: &str,
601    expected_kinds: &[(&str, &str, &str)],
602) -> Result<()> {
603    let members = schema
604        .pointer(&format!("/$defs/{union}/anyOf"))
605        .and_then(Value::as_array)
606        .with_context(|| format!("missing {schema_name} {union} union"))?;
607    let mut actual = BTreeMap::new();
608    for member in members {
609        let reference = member
610            .get("$ref")
611            .and_then(Value::as_str)
612            .with_context(|| format!("{schema_name} {union} member is not a reference"))?;
613        let structure = reference
614            .strip_prefix("#/$defs/")
615            .with_context(|| format!("{schema_name} {union} reference leaves $defs"))?;
616        let kind = literal_kind_for_structure(schema, structure)?;
617        if actual.insert(structure, kind).is_some() {
618            bail!("duplicate {schema_name} {union} member {structure}");
619        }
620    }
621    let expected = expected_kinds
622        .iter()
623        .map(|(structure, kind, _)| (*structure, *kind))
624        .collect::<BTreeMap<_, _>>();
625    if actual != expected {
626        bail!("{schema_name} {union} union changed; update exact-kind projection");
627    }
628    Ok(())
629}
630
631fn literal_kind_for_structure<'a>(schema: &'a Value, structure: &str) -> Result<&'a str> {
632    if let Some(kind) = schema
633        .pointer(&format!("/$defs/{structure}/properties/kind/const"))
634        .and_then(Value::as_str)
635    {
636        return Ok(kind);
637    }
638    let reference = schema
639        .pointer(&format!("/$defs/{structure}/allOf/0/$ref"))
640        .and_then(Value::as_str)
641        .with_context(|| format!("missing literal kind or base operation for {structure}"))?;
642    let base = reference
643        .strip_prefix("#/$defs/")
644        .with_context(|| format!("{structure} base operation reference leaves $defs"))?;
645    schema
646        .pointer(&format!("/$defs/{base}/properties/kind/const"))
647        .and_then(Value::as_str)
648        .with_context(|| format!("missing literal kind for {structure} base {base}"))
649}
650
651fn project_generated_presence(
652    schema_name: &str,
653    published_schema: &Value,
654    source: String,
655) -> Result<String> {
656    if !uses_strict_presence_projection(schema_name) {
657        return Ok(source);
658    }
659    let mut projected = source;
660    let is_document = matches!(
661        schema_name,
662        "BoardPlotDocument.json"
663            | "FootprintPlotDocument.json"
664            | "SchematicPlotDocument.json"
665            | "SymbolPlotDocument.json"
666    );
667    if is_document
668        && matches!(
669            schema_name,
670            "FootprintPlotDocument.json" | "SchematicPlotDocument.json" | "SymbolPlotDocument.json"
671        )
672    {
673        let original = r#"    #[serde(default, skip_serializing_if = "::std::vec::Vec::is_empty")]
674    pub render_cache_polygons: ::std::vec::Vec<::std::vec::Vec<PlotterPoint>>,"#;
675        let replacement = r#"    #[serde(
676        default,
677        deserialize_with = "crate::reject_present_render_cache_polygons",
678        skip_serializing_if = "::std::vec::Vec::is_empty"
679    )]
680    pub render_cache_polygons: ::std::vec::Vec<::std::vec::Vec<PlotterPoint>>,"#;
681        if !projected.contains(original) {
682            bail!("{schema_name} Text render-cache polygon projection changed");
683        }
684        projected = projected.replace(original, replacement);
685    }
686    if is_document {
687        for (structure, _, deserializer) in PLOTTER_OPERATION_KINDS {
688            projected = project_kind_deserializer(projected, structure, deserializer)?;
689        }
690    }
691    if schema_name == "BoardPlotDocument.json" {
692        for (structure, _, deserializer) in BOARD_FOOTPRINT_OPERATION_KINDS {
693            projected = project_kind_deserializer(projected, structure, deserializer)?;
694        }
695    }
696    if schema_name == "SchematicPlotDocument.json" {
697        for (structure, _, deserializer) in SCHEMATIC_RECORD_KINDS {
698            projected = project_kind_deserializer(projected, structure, deserializer)?;
699        }
700        for (structure, _, deserializer) in SCHEMATIC_SYMBOL_OPERATION_KINDS
701            .into_iter()
702            .filter(|(structure, _, _)| structure.starts_with("SchematicSymbol"))
703        {
704            projected = project_kind_deserializer(projected, structure, deserializer)?;
705        }
706        for (structure, _, deserializer) in SCHEMATIC_SHEET_OPERATION_KINDS
707            .into_iter()
708            .filter(|(structure, _, _)| structure.starts_with("SchematicSheet"))
709        {
710            projected = project_kind_deserializer(projected, structure, deserializer)?;
711        }
712        projected = project_schematic_record_string(projected)?;
713        projected = project_schematic_junction_color(projected)?;
714        projected = project_schematic_segment_layers(projected)?;
715    }
716    projected = project_schema_presence(schema_name, published_schema, projected)?;
717    // Presence and deterministic-map substitutions can cross rustfmt's line-width
718    // boundary, so normalize the fully projected source as the final step.
719    rustfmt(&projected)
720}
721
722fn project_schematic_segment_layers(mut source: String) -> Result<String> {
723    let marker = "pub struct ThickSegmentOperation {";
724    let start = source
725        .find(marker)
726        .context("missing generated ThickSegmentOperation")?;
727    let end = source[start..]
728        .find("\n}")
729        .map(|offset| start + offset)
730        .context("unterminated generated ThickSegmentOperation")?;
731    let field = r#"    #[serde(default, skip_serializing_if = "::std::vec::Vec::is_empty")]
732    pub layers: ::std::vec::Vec<::std::string::String>,"#;
733    let offset = source[start..end]
734        .find(field)
735        .map(|offset| start + offset)
736        .context("missing generated ThickSegmentOperation.layers")?;
737    let replacement = r#"    #[serde(
738        default,
739        deserialize_with = "crate::reject_present_schematic_segment_layers",
740        skip_serializing_if = "::std::vec::Vec::is_empty"
741    )]
742    pub layers: ::std::vec::Vec<::std::string::String>,"#;
743    source.replace_range(offset..offset + field.len(), replacement);
744    Ok(source)
745}
746
747#[derive(Clone, Copy, Debug, Eq, PartialEq)]
748enum FieldPresence {
749    OptionalNonnullable,
750    OptionalNullable,
751    RequiredNullable,
752}
753
754fn uses_strict_presence_projection(schema_name: &str) -> bool {
755    matches!(
756        schema_name,
757        "CompiledSchematicGraph.json"
758            | "SourceBundleManifest.json"
759            | "BoardPlotDocument.json"
760            | "BoardPlotRequest.json"
761            | "BoardPlotResult.json"
762            | "FootprintPlotDocument.json"
763            | "FootprintPlotRequest.json"
764            | "FootprintPlotResult.json"
765            | "SymbolPlotDocument.json"
766            | "SymbolPlotRequest.json"
767            | "SymbolPlotResult.json"
768            | "SchematicPlotDocument.json"
769            | "SchematicPlotRequest.json"
770            | "SchematicPlotResult.json"
771    )
772}
773
774fn project_schema_presence(schema_name: &str, schema: &Value, source: String) -> Result<String> {
775    let rules = schema_presence_rules(schema_name, schema)?;
776    let mut syntax =
777        syn::parse_file(&source).context("parse generated Rust for presence projection")?;
778    let mut seen = BTreeSet::new();
779    let mut projected_optionals = 0usize;
780    let mut required_nullables = 0usize;
781
782    for item in &mut syntax.items {
783        let syn::Item::Struct(structure) = item else {
784            continue;
785        };
786        let syn::Fields::Named(fields) = &mut structure.fields else {
787            continue;
788        };
789        let structure_name = structure.ident.to_string();
790        for field in &mut fields.named {
791            let Some(field_ident) = &field.ident else {
792                continue;
793            };
794            let rust_name = field_ident.to_string();
795            let wire_name = serde_field_name(field)?.unwrap_or_else(|| rust_name.clone());
796            let key = (structure_name.clone(), wire_name.clone());
797            let Some(presence) = rules.get(&key).copied() else {
798                continue;
799            };
800            seen.insert(key.clone());
801            if !is_option_type(&field.ty) {
802                // Vec/map/defaulted scalar projections already reject JSON null through
803                // their native deserializers; only Option<T> needs a presence projection.
804                continue;
805            }
806            let (optional_count, required_count) =
807                project_presence_field(schema_name, field, presence, &wire_name, &rust_name, &key)?;
808            projected_optionals += optional_count;
809            required_nullables += required_count;
810        }
811    }
812
813    let missing = rules
814        .keys()
815        .filter(|key| !seen.contains(*key))
816        .map(|(structure, field)| format!("{structure}.{field}"))
817        .collect::<Vec<_>>();
818    if !missing.is_empty() {
819        bail!(
820            "{schema_name} generated presence fields are missing: {}",
821            missing.join(", ")
822        );
823    }
824    let expected_required_nullables = rules
825        .values()
826        .filter(|presence| **presence == FieldPresence::RequiredNullable)
827        .count();
828    if required_nullables != expected_required_nullables {
829        bail!(
830            "{schema_name} required-nullable projection changed: {required_nullables} != {expected_required_nullables}"
831        );
832    }
833    if rules
834        .values()
835        .any(|presence| *presence == FieldPresence::OptionalNonnullable)
836        && projected_optionals == 0
837    {
838        bail!("{schema_name} has no projected optional nonnullable Option<T> fields");
839    }
840    Ok(prettyplease::unparse(&syntax))
841}
842
843fn project_presence_field(
844    schema_name: &str,
845    field: &mut syn::Field,
846    presence: FieldPresence,
847    wire_name: &str,
848    rust_name: &str,
849    key: &(String, String),
850) -> Result<(usize, usize)> {
851    let span = field
852        .ident
853        .as_ref()
854        .context("generated field has no name")?
855        .span();
856    match presence {
857        FieldPresence::OptionalNonnullable => {
858            let replacement = if wire_name == rust_name {
859                syn::parse_quote!(#[serde(
860                    default,
861                    deserialize_with = "crate::deserialize_present_nonnull",
862                    skip_serializing_if = "::std::option::Option::is_none"
863                )])
864            } else {
865                let wire_name = syn::LitStr::new(wire_name, span);
866                syn::parse_quote!(#[serde(
867                    rename = #wire_name,
868                    default,
869                    deserialize_with = "crate::deserialize_present_nonnull",
870                    skip_serializing_if = "::std::option::Option::is_none"
871                )])
872            };
873            replace_serde_presence_attr(field, replacement)?;
874            Ok((1, 0))
875        }
876        FieldPresence::RequiredNullable => {
877            let replacement = if wire_name == rust_name {
878                syn::parse_quote!(#[serde(
879                    deserialize_with = "crate::deserialize_required_nullable"
880                )])
881            } else {
882                let wire_name = syn::LitStr::new(wire_name, span);
883                syn::parse_quote!(#[serde(
884                    rename = #wire_name,
885                    deserialize_with = "crate::deserialize_required_nullable"
886                )])
887            };
888            replace_serde_presence_attr(field, replacement)?;
889            Ok((0, 1))
890        }
891        FieldPresence::OptionalNullable => {
892            if key != &("SchematicJunctionPlotRecord".to_owned(), "color".to_owned())
893                || !is_nested_option_type(&field.ty)
894                || !has_deserializer(field, "deserialize_present_nullable_string")
895            {
896                bail!(
897                    "{schema_name} optional-nullable projection changed at {}.{}",
898                    key.0,
899                    key.1
900                );
901            }
902            Ok((0, 0))
903        }
904    }
905}
906
907fn serde_field_name(field: &syn::Field) -> Result<Option<String>> {
908    let mut rename = None;
909    for attribute in field
910        .attrs
911        .iter()
912        .filter(|attribute| attribute.path().is_ident("serde"))
913    {
914        attribute.parse_nested_meta(|meta| {
915            if meta.path.is_ident("rename") {
916                let value = meta.value()?;
917                rename = Some(value.parse::<syn::LitStr>()?.value());
918            } else if meta.input.peek(syn::Token![=]) {
919                let _ = meta.value()?.parse::<syn::Expr>()?;
920            }
921            Ok(())
922        })?;
923    }
924    Ok(rename)
925}
926
927fn replace_serde_presence_attr(field: &mut syn::Field, replacement: syn::Attribute) -> Result<()> {
928    let serde_attributes = field
929        .attrs
930        .iter()
931        .filter(|attribute| attribute.path().is_ident("serde"))
932        .count();
933    if serde_attributes > 1 {
934        bail!("generated optional field has multiple serde attributes");
935    }
936    field
937        .attrs
938        .retain(|attribute| !attribute.path().is_ident("serde"));
939    field.attrs.push(replacement);
940    Ok(())
941}
942
943fn has_deserializer(field: &syn::Field, needle: &str) -> bool {
944    field.attrs.iter().any(|attribute| {
945        attribute.path().is_ident("serde")
946            && matches!(&attribute.meta, syn::Meta::List(list) if list.tokens.to_string().contains(needle))
947    })
948}
949
950fn is_option_type(ty: &syn::Type) -> bool {
951    let syn::Type::Path(path) = ty else {
952        return false;
953    };
954    path.path
955        .segments
956        .last()
957        .is_some_and(|segment| segment.ident == "Option")
958}
959
960fn is_nested_option_type(ty: &syn::Type) -> bool {
961    let syn::Type::Path(path) = ty else {
962        return false;
963    };
964    let Some(segment) = path.path.segments.last() else {
965        return false;
966    };
967    let syn::PathArguments::AngleBracketed(arguments) = &segment.arguments else {
968        return false;
969    };
970    arguments.args.iter().any(
971        |argument| matches!(argument, syn::GenericArgument::Type(inner) if is_option_type(inner)),
972    )
973}
974
975fn schema_presence_rules(
976    schema_name: &str,
977    schema: &Value,
978) -> Result<BTreeMap<(String, String), FieldPresence>> {
979    let mut objects = BTreeMap::new();
980    objects.insert(
981        schema_name.trim_end_matches(".json").to_owned() + "A0",
982        schema,
983    );
984    if let Some(definitions) = schema.get("$defs").and_then(Value::as_object) {
985        objects.extend(
986            definitions
987                .iter()
988                .map(|(name, value)| (name.clone(), value)),
989        );
990    }
991
992    let mut rules = BTreeMap::new();
993    for (structure, object) in objects {
994        let mut properties = BTreeMap::new();
995        let mut required = BTreeSet::new();
996        collect_object_shape(schema, object, &mut properties, &mut required)?;
997        for (field, property) in properties {
998            let nullable = schema_allows_null(property);
999            let presence = match (required.contains(&field), nullable) {
1000                (false, false) => Some(FieldPresence::OptionalNonnullable),
1001                (false, true) => Some(FieldPresence::OptionalNullable),
1002                (true, true) => Some(FieldPresence::RequiredNullable),
1003                (true, false) => None,
1004            };
1005            if let Some(presence) = presence {
1006                rules.insert((structure.clone(), field.clone()), presence);
1007            }
1008        }
1009    }
1010    Ok(rules)
1011}
1012
1013fn collect_object_shape<'a>(
1014    root: &'a Value,
1015    object: &'a Value,
1016    properties: &mut BTreeMap<String, &'a Value>,
1017    required: &mut BTreeSet<String>,
1018) -> Result<()> {
1019    if let Some(reference) = object.get("$ref").and_then(Value::as_str) {
1020        let name = reference
1021            .strip_prefix("#/$defs/")
1022            .with_context(|| format!("presence reference leaves $defs: {reference}"))?;
1023        let target = root
1024            .pointer(&format!("/$defs/{name}"))
1025            .with_context(|| format!("missing presence reference {reference}"))?;
1026        collect_object_shape(root, target, properties, required)?;
1027    }
1028    if let Some(parts) = object.get("allOf").and_then(Value::as_array) {
1029        for part in parts {
1030            collect_object_shape(root, part, properties, required)?;
1031        }
1032    }
1033    if let Some(fields) = object.get("properties").and_then(Value::as_object) {
1034        properties.extend(fields.iter().map(|(name, value)| (name.clone(), value)));
1035    }
1036    if let Some(names) = object.get("required").and_then(Value::as_array) {
1037        for name in names.iter().filter_map(Value::as_str) {
1038            if !properties.contains_key(name) {
1039                bail!("required presence field {name} has no property");
1040            }
1041            required.insert(name.to_owned());
1042        }
1043    }
1044    Ok(())
1045}
1046
1047fn schema_allows_null(schema: &Value) -> bool {
1048    match schema.get("type") {
1049        Some(Value::String(kind)) if kind == "null" => return true,
1050        Some(Value::Array(kinds))
1051            if kinds
1052                .iter()
1053                .any(|kind| kind.as_str().is_some_and(|kind| kind == "null")) =>
1054        {
1055            return true;
1056        }
1057        _ => {}
1058    }
1059    ["anyOf", "oneOf"].into_iter().any(|key| {
1060        schema
1061            .get(key)
1062            .and_then(Value::as_array)
1063            .is_some_and(|members| members.iter().any(schema_allows_null))
1064    })
1065}
1066
1067fn project_schematic_junction_color(mut source: String) -> Result<String> {
1068    let structure = "SchematicJunctionPlotRecord";
1069    let structure_marker = format!("pub struct {structure} {{");
1070    let structure_start = source
1071        .find(&structure_marker)
1072        .with_context(|| format!("missing generated {structure}"))?;
1073    let structure_end = source[structure_start..]
1074        .find("\n}")
1075        .map(|offset| structure_start + offset)
1076        .with_context(|| format!("unterminated generated {structure}"))?;
1077    let field = r#"    #[serde(default, skip_serializing_if = "::std::option::Option::is_none")]
1078    pub color: ::std::option::Option<::std::string::String>,"#;
1079    let field_offset = source[structure_start..structure_end]
1080        .find(field)
1081        .map(|offset| structure_start + offset)
1082        .with_context(|| format!("missing generated {structure}.color"))?;
1083    let replacement = r#"    #[serde(
1084        default,
1085        deserialize_with = "crate::deserialize_present_nullable_string",
1086        skip_serializing_if = "::std::option::Option::is_none"
1087    )]
1088    pub color: ::std::option::Option<::std::option::Option<::std::string::String>>,"#;
1089    source.replace_range(field_offset..field_offset + field.len(), replacement);
1090    Ok(source)
1091}
1092
1093fn project_schematic_record_string(source: String) -> Result<String> {
1094    let hash_map = "::std::collections::HashMap<::std::string::String, ::std::string::String>";
1095    if !source.contains(hash_map) {
1096        bail!("SchematicPlotDocument.json RecordString map projection changed");
1097    }
1098    Ok(source.replace(
1099        hash_map,
1100        "::std::collections::BTreeMap<::std::string::String, ::std::string::String>",
1101    ))
1102}
1103
1104fn project_kind_deserializer(
1105    mut source: String,
1106    structure: &str,
1107    deserializer: &str,
1108) -> Result<String> {
1109    let structure_marker = format!("pub struct {structure} {{");
1110    let structure_start = source
1111        .find(&structure_marker)
1112        .with_context(|| format!("missing generated {structure}"))?;
1113    let structure_end = source[structure_start..]
1114        .find("\n}")
1115        .map(|offset| structure_start + offset)
1116        .with_context(|| format!("unterminated generated {structure}"))?;
1117    let field = "    pub kind: ::std::string::String,";
1118    let field_offset = source[structure_start..structure_end]
1119        .find(field)
1120        .map(|offset| structure_start + offset)
1121        .with_context(|| format!("missing generated {structure}.kind"))?;
1122    let replacement =
1123        format!("    #[serde(deserialize_with = \"crate::{deserializer}\")]\n{field}");
1124    source.replace_range(field_offset..field_offset + field.len(), &replacement);
1125    Ok(source)
1126}
1127
1128fn generate(schema_name: &str, value: Value) -> Result<String> {
1129    let schema: RootSchema = serde_json::from_value(value)?;
1130    let mut settings = TypeSpaceSettings::default();
1131    settings.with_struct_builder(false);
1132    settings.with_replacement(
1133        "JavaScriptSafeInteger",
1134        "crate::JavaScriptSafeInteger",
1135        [].into_iter(),
1136    );
1137    if !text_contract::replace_text_contract_types(schema_name, &mut settings) {
1138        settings.with_replacement(
1139            "TextSafeInteger",
1140            "crate::JavaScriptSafeInteger",
1141            [].into_iter(),
1142        );
1143    }
1144    settings.with_replacement(
1145        "NonNegativeFiniteFloat",
1146        "crate::NonNegativeFiniteFloat",
1147        [].into_iter(),
1148    );
1149    settings.with_replacement("FiniteFloat", "crate::FiniteFloat", [].into_iter());
1150    settings.with_replacement("PositiveUint32", "crate::PositiveU32", [].into_iter());
1151    settings.with_replacement(
1152        "SchematicPositiveUint32",
1153        "::std::num::NonZeroU32",
1154        [].into_iter(),
1155    );
1156    settings.with_replacement(
1157        "SchematicDefaultLineWidthNm",
1158        "crate::SchematicDefaultLineWidthNm",
1159        [].into_iter(),
1160    );
1161    settings.with_replacement(
1162        "SchematicTextOffsetRatio",
1163        "crate::NonNegativeFiniteFloat",
1164        [].into_iter(),
1165    );
1166    settings.with_replacement("StableTextId", "crate::StableTextId", [].into_iter());
1167    settings.with_replacement("NonEmptyText", "::std::string::String", [].into_iter());
1168    let mut type_space = TypeSpace::new(&settings);
1169    type_space.add_root_schema(schema)?;
1170    let body = type_space.to_stream().to_string();
1171    let source =
1172        format!("// Generated from TypeSpec JSON Schema through typify. Do not edit.\n\n{body}\n");
1173    let syntax = syn::parse_file(&source).context("parse generated Rust")?;
1174    rustfmt(&prettyplease::unparse(&syntax))
1175}
1176
1177fn rustfmt(source: &str) -> Result<String> {
1178    let mut child = Command::new("rustfmt")
1179        .args(["--edition", "2024", "--emit", "stdout"])
1180        .stdin(Stdio::piped())
1181        .stdout(Stdio::piped())
1182        .spawn()
1183        .context("start rustfmt for generated contract")?;
1184    child
1185        .stdin
1186        .take()
1187        .context("open rustfmt stdin")?
1188        .write_all(source.as_bytes())?;
1189    let output = child.wait_with_output()?;
1190    if !output.status.success() {
1191        bail!("rustfmt rejected generated contract source");
1192    }
1193    String::from_utf8(output.stdout).context("rustfmt output was not UTF-8")
1194}
1195
1196fn promote_disjoint_record_unions(schema: &mut Value) {
1197    // TypeSpec emits record unions as `anyOf`. The board record variants are
1198    // value-disjoint on their `kind` discriminators, but typify's structural
1199    // exclusivity check cannot see const/enum property values (graphic and
1200    // track_arc records share the same required property names), so it
1201    // degrades the union to an unusable `subtype_N` option struct. Carrying
1202    // the disjointness assertion as `oneOf` in the Rust projection yields a
1203    // proper enum; the published schema keeps `anyOf` alongside the other
1204    // record unions.
1205    for pointer in [
1206        "/$defs/BoardPlotRecord",
1207        "/$defs/BoardFootprintOperation",
1208        "/$defs/SchematicPlotRecord",
1209    ] {
1210        if let Some(record) = schema.pointer_mut(pointer).and_then(Value::as_object_mut)
1211            && let Some(members) = record.remove("anyOf")
1212        {
1213            record.insert("oneOf".to_owned(), members);
1214        }
1215    }
1216}
1217
1218fn project_tri_state_via_drill_layers(schema: &mut Value) {
1219    // The established board serializer distinguishes an absent `layers` key
1220    // (layerless graphic circles) from a present-but-empty `layers` array
1221    // (drill circles of unrouted vias). typify folds optional arrays into
1222    // `Vec` with `skip_serializing_if(is_empty)`, which cannot express the
1223    // present-but-empty state, so the Rust projection widens the board
1224    // circle's `layers` to a nullable array and gains `Option<Vec<String>>`.
1225    // The published schema keeps the plain optional array.
1226    if schema.pointer("/$defs/BoardPlotRecord").is_some()
1227        && let Some(layers) = schema
1228            .pointer_mut("/$defs/CircleOperation/properties/layers")
1229            .and_then(Value::as_object_mut)
1230    {
1231        layers.insert("type".to_owned(), serde_json::json!(["array", "null"]));
1232    }
1233}
1234
1235fn project_schematic_request_fields(schema_name: &str, schema: &mut Value) -> Result<()> {
1236    if schema_name != "SchematicPlotRequest.json" {
1237        return Ok(());
1238    }
1239    let bounded = serde_json::json!({
1240        "type": "integer",
1241        "minimum": 1,
1242        "maximum": 4_294_967_295_u64,
1243    });
1244    for field in ["sheet_index", "sheet_count"] {
1245        let pointer = format!("/properties/{field}");
1246        let property = schema
1247            .pointer_mut(&pointer)
1248            .with_context(|| format!("missing SchematicPlotRequest.{field}"))?;
1249        if property != &bounded {
1250            bail!("SchematicPlotRequest.{field} positive-u32 schema changed");
1251        }
1252        *property = serde_json::json!({"$ref": "#/$defs/SchematicPositiveUint32"});
1253    }
1254    let definitions = schema
1255        .pointer_mut("/$defs")
1256        .and_then(Value::as_object_mut)
1257        .context("missing SchematicPlotRequest $defs")?;
1258    definitions.insert("SchematicPositiveUint32".to_owned(), bounded);
1259
1260    let default_width = serde_json::json!({
1261        "type": "integer",
1262        "minimum": 84_700,
1263        "maximum": 9_007_199_254_740_991_i64,
1264    });
1265    let default_width_property = schema
1266        .pointer("/properties/default_line_width_nm")
1267        .context("missing SchematicPlotRequest.default_line_width_nm")?;
1268    let mut default_width_definition = schema
1269        .pointer("/$defs/SchematicDefaultLineWidthNm")
1270        .cloned()
1271        .context("missing SchematicDefaultLineWidthNm definition")?;
1272    default_width_definition
1273        .as_object_mut()
1274        .context("SchematicDefaultLineWidthNm must be an object")?
1275        .remove("description");
1276    if default_width_property != &serde_json::json!({"$ref": "#/$defs/SchematicDefaultLineWidthNm"})
1277        || default_width_definition != default_width
1278    {
1279        bail!("SchematicPlotRequest.default_line_width_nm schema changed");
1280    }
1281
1282    let ratio = serde_json::json!({
1283        "type": "number",
1284        "minimum": 0,
1285        "maximum": 1.7976931348623157e308_f64,
1286    });
1287    let ratio_property = schema
1288        .pointer("/properties/text_offset_ratio")
1289        .context("missing SchematicPlotRequest.text_offset_ratio")?;
1290    let mut ratio_definition = schema
1291        .pointer("/$defs/SchematicTextOffsetRatio")
1292        .cloned()
1293        .context("missing SchematicTextOffsetRatio definition")?;
1294    ratio_definition
1295        .as_object_mut()
1296        .context("SchematicTextOffsetRatio must be an object")?
1297        .remove("description");
1298    if ratio_property != &serde_json::json!({"$ref": "#/$defs/SchematicTextOffsetRatio"})
1299        || ratio_definition != ratio
1300    {
1301        bail!("SchematicPlotRequest.text_offset_ratio schema changed");
1302    }
1303    Ok(())
1304}
1305
1306fn project_for_typify(value: &mut Value) {
1307    match value {
1308        Value::Object(object) => {
1309            object.remove("$schema");
1310            if matches!(
1311                object.get("pattern").and_then(Value::as_str),
1312                Some("^(0|[1-9][0-9]{0,19})$")
1313                    | Some("^[0-9a-f]{64}$")
1314                    | Some("^[ -~]{4}$")
1315                    | Some("^[A-Za-z0-9][A-Za-z0-9._:-]*$")
1316            ) {
1317                // JSON Schema and the promoted semantic validators retain
1318                // the closed string grammars. Avoid adding a regex runtime to
1319                // generated Rust merely for small fixed tags and hashes.
1320                object.remove("pattern");
1321            }
1322            if let Some(entry) = object.remove("unevaluatedProperties") {
1323                let projected = if entry == serde_json::json!({"not": {}}) {
1324                    Value::Bool(false)
1325                } else {
1326                    entry
1327                };
1328                object
1329                    .entry("additionalProperties".to_owned())
1330                    .or_insert(projected);
1331            }
1332            for child in object.values_mut() {
1333                project_for_typify(child);
1334            }
1335        }
1336        Value::Array(values) => {
1337            for child in values {
1338                project_for_typify(child);
1339            }
1340        }
1341        _ => {}
1342    }
1343}