kicad_monkey_core/configuration/
library_table.rs1use crate::sexpr::{self, Error, ErrorKind, Sexp};
5use crate::sexpr_projection::StructuralIndex;
6
7#[derive(Clone, Copy, Debug, Eq, PartialEq)]
8pub enum TableKind {
9 Symbol,
10 Footprint,
11}
12
13impl TableKind {
14 pub fn head(self) -> &'static str {
15 match self {
16 Self::Symbol => "sym_lib_table",
17 Self::Footprint => "fp_lib_table",
18 }
19 }
20}
21
22#[derive(Clone, Debug, Eq, PartialEq)]
23pub struct LibraryEntry {
24 pub name: String,
25 pub library_type: String,
26 pub uri: String,
27 pub options: String,
28 pub description: String,
29 pub hidden: bool,
30}
31
32#[derive(Clone, Debug)]
33pub struct ExistingEntry<'a> {
34 pub name: String,
35 pub library_type: String,
36 pub uri: String,
37 pub source: &'a str,
38}
39
40pub struct LibraryTableView<'a> {
41 kind: TableKind,
42 entries: Vec<ExistingEntry<'a>>,
43}
44
45impl<'a> LibraryTableView<'a> {
46 pub fn parse(source: &'a str, kind: TableKind) -> Result<Self, Error> {
47 let root = sexpr::parse(source)?;
48 if list(&root)
49 .and_then(|values| values.first())
50 .and_then(scalar)
51 != Some(kind.head())
52 {
53 return Err(invalid("Unexpected KiCad library-table root"));
54 }
55 let index = StructuralIndex::new(source)?;
56 let mut entries: Vec<ExistingEntry<'a>> = Vec::new();
57 let mut positions = std::collections::HashMap::<String, usize>::new();
58 for form in index
59 .forms()
60 .iter()
61 .filter(|form| form.depth == 1 && form.head.as_deref() == Some("lib"))
62 {
63 let raw = form.text(source)?;
64 let value = sexpr::parse(raw)?;
65 let name = field(&value, "name").unwrap_or_default();
66 if name.is_empty() {
67 continue;
68 }
69 let entry = ExistingEntry {
70 name: name.into(),
71 library_type: field(&value, "type").unwrap_or_default().into(),
72 uri: field(&value, "uri").unwrap_or_default().into(),
73 source: raw,
74 };
75 if let Some(&prior) = positions.get(name) {
76 entries[prior] = entry;
77 } else {
78 positions.insert(name.to_owned(), entries.len());
79 entries.push(entry);
80 }
81 }
82 Ok(Self { kind, entries })
83 }
84
85 pub fn entries(&self) -> &[ExistingEntry<'a>] {
86 &self.entries
87 }
88
89 pub fn render(&self, generated: &[LibraryEntry], retained: &[usize]) -> Result<String, Error> {
90 let mut result = format!("({}\n (version 7)\n", self.kind.head());
91 for entry in generated {
92 result.push_str(" ");
93 result.push_str(&render_entry(entry)?);
94 result.push('\n');
95 }
96 for &index in retained {
97 let entry = self
98 .entries
99 .get(index)
100 .ok_or_else(|| invalid("Library-table retained index is out of range"))?;
101 result.push_str(" ");
102 result.push_str(entry.source);
103 result.push('\n');
104 }
105 result.push_str(")\n");
106 Ok(result)
107 }
108}
109
110pub fn render_entry(entry: &LibraryEntry) -> Result<String, Error> {
111 let mut fields = vec![Sexp::Atom("lib".into())];
112 for (name, value) in [
113 ("name", &entry.name),
114 ("type", &entry.library_type),
115 ("uri", &entry.uri),
116 ("options", &entry.options),
117 ("descr", &entry.description),
118 ] {
119 fields.push(Sexp::List(vec![
120 Sexp::Atom(name.into()),
121 Sexp::Quoted(value.clone()),
122 ]));
123 }
124 if entry.hidden {
125 fields.push(Sexp::List(vec![Sexp::Atom("hidden".into())]));
126 }
127 sexpr::build(&Sexp::List(fields))
128}
129
130fn scalar(value: &Sexp) -> Option<&str> {
131 match value {
132 Sexp::Atom(text) | Sexp::Quoted(text) => Some(text),
133 _ => None,
134 }
135}
136
137fn field<'a>(root: &'a Sexp, name: &str) -> Option<&'a str> {
138 list(root)?
139 .iter()
140 .filter_map(list)
141 .find(|values| values.first().and_then(scalar) == Some(name))?
142 .get(1)
143 .and_then(scalar)
144}
145
146fn list(value: &Sexp) -> Option<&[Sexp]> {
147 match value {
148 Sexp::List(values) => Some(values),
149 _ => None,
150 }
151}
152
153fn invalid(message: &'static str) -> Error {
154 Error::build(ErrorKind::InvalidBuildValue, message)
155}