1use crate::value::Tagged;
27use crate::BindingError;
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31#[non_exhaustive]
32pub enum FieldKind {
33 Text,
35 Id,
37 Ids,
39 Reals,
41 Integer,
43 Bool,
45 Texts,
47 Attributes,
49}
50
51#[derive(Debug, Clone, Copy)]
53#[non_exhaustive]
54pub struct FieldSpec {
55 pub name: &'static str,
57 pub camel: &'static str,
59 pub kind: FieldKind,
61 pub required: bool,
63}
64
65#[derive(Debug, Clone, Copy)]
67#[non_exhaustive]
68pub struct OpSpec {
69 pub name: &'static str,
71 pub camel: &'static str,
73 pub fields: &'static [FieldSpec],
75}
76
77impl OpSpec {
78 pub fn field(&self, key: &str) -> Option<&'static FieldSpec> {
80 self.fields
81 .iter()
82 .find(|f| f.name.eq_ignore_ascii_case(key) || f.camel.eq_ignore_ascii_case(key))
83 }
84}
85
86const fn field(name: &'static str, camel: &'static str, kind: FieldKind) -> FieldSpec {
87 FieldSpec {
88 name,
89 camel,
90 kind,
91 required: false,
92 }
93}
94
95const fn required(name: &'static str, camel: &'static str, kind: FieldKind) -> FieldSpec {
96 FieldSpec {
97 name,
98 camel,
99 kind,
100 required: true,
101 }
102}
103
104use FieldKind as K;
105
106const TYPE: FieldSpec = required("type", "type", K::Text);
107const ATTRIBUTES: FieldSpec = field("attributes", "attributes", K::Attributes);
108const OWNER: FieldSpec = field("owner_history", "ownerHistory", K::Id);
109const REPLACE: FieldSpec = field("replace", "replace", K::Bool);
110const REPRESENTATION: FieldSpec = required("representation", "representation", K::Id);
111
112pub const OPS: &[OpSpec] = &[
114 OpSpec {
115 name: "create",
116 camel: "create",
117 fields: &[TYPE, ATTRIBUTES],
118 },
119 OpSpec {
120 name: "edit",
121 camel: "edit",
122 fields: &[
123 required("entity", "entity", K::Id),
124 required("attributes", "attributes", K::Attributes),
125 ],
126 },
127 OpSpec {
128 name: "remove",
129 camel: "remove",
130 fields: &[required("entity", "entity", K::Id)],
131 },
132 OpSpec {
133 name: "project",
134 camel: "project",
135 fields: &[ATTRIBUTES, OWNER],
136 },
137 OpSpec {
138 name: "spatial",
139 camel: "spatial",
140 fields: &[
141 TYPE,
142 required("parent", "parent", K::Id),
143 ATTRIBUTES,
144 field("placement", "placement", K::Id),
145 OWNER,
146 ],
147 },
148 OpSpec {
149 name: "product",
150 camel: "product",
151 fields: &[
152 TYPE,
153 field("container", "container", K::Id),
154 ATTRIBUTES,
155 field("placement", "placement", K::Id),
156 field("type_object", "typeObject", K::Id),
157 OWNER,
158 ],
159 },
160 OpSpec {
161 name: "type_object",
162 camel: "typeObject",
163 fields: &[TYPE, ATTRIBUTES, OWNER],
164 },
165 OpSpec {
166 name: "assign_type",
167 camel: "assignType",
168 fields: &[
169 required("type_object", "typeObject", K::Id),
170 required("objects", "objects", K::Ids),
171 OWNER,
172 field("map_representations", "mapRepresentations", K::Bool),
173 field("mapping_target", "mappingTarget", K::Id),
174 field("material_usage", "materialUsage", K::Bool),
175 field("layer_set_direction", "layerSetDirection", K::Text),
176 field("predefined_type", "predefinedType", K::Text),
177 REPLACE,
178 ],
179 },
180 OpSpec {
181 name: "contain",
182 camel: "contain",
183 fields: &[
184 required("structure", "structure", K::Id),
185 required("elements", "elements", K::Ids),
186 OWNER,
187 REPLACE,
188 ],
189 },
190 OpSpec {
191 name: "aggregate",
192 camel: "aggregate",
193 fields: &[
194 required("parent", "parent", K::Id),
195 required("parts", "parts", K::Ids),
196 OWNER,
197 REPLACE,
198 ],
199 },
200 OpSpec {
201 name: "placement",
202 camel: "placement",
203 fields: &[
204 field("relative_to", "relativeTo", K::Id),
205 field("location", "location", K::Reals),
206 field("axis", "axis", K::Reals),
207 field("ref_direction", "refDirection", K::Reals),
208 ],
209 },
210 OpSpec {
211 name: "shape_representation",
212 camel: "shapeRepresentation",
213 fields: &[
214 required("context", "context", K::Id),
215 required("items", "items", K::Ids),
216 field("identifier", "identifier", K::Text),
217 field("representation_type", "representationType", K::Text),
218 ],
219 },
220 OpSpec {
221 name: "assign_representation",
222 camel: "assignRepresentation",
223 fields: &[REPRESENTATION, required("to", "to", K::Id)],
224 },
225 OpSpec {
226 name: "unassign_representation",
227 camel: "unassignRepresentation",
228 fields: &[REPRESENTATION, required("from", "from", K::Id)],
229 },
230 OpSpec {
231 name: "copy_representation",
232 camel: "copyRepresentation",
233 fields: &[REPRESENTATION],
234 },
235 OpSpec {
236 name: "remove_representation",
237 camel: "removeRepresentation",
238 fields: &[REPRESENTATION],
239 },
240 OpSpec {
241 name: "copy_product",
242 camel: "copyProduct",
243 fields: &[
244 required("product", "product", K::Id),
245 field("offset", "offset", K::Reals),
246 field("placement", "placement", K::Id),
247 field("openings", "openings", K::Bool),
248 field("fillings", "fillings", K::Bool),
249 field("container", "container", K::Bool),
250 field("aggregate", "aggregate", K::Bool),
251 ],
252 },
253 OpSpec {
254 name: "copy_entity",
255 camel: "copyEntity",
256 fields: &[
257 required("entity", "entity", K::Id),
258 field("copy", "copy", K::Texts),
259 field("share", "share", K::Texts),
260 field("copy_roots", "copyRoots", K::Bool),
261 field("copy_definitions", "copyDefinitions", K::Bool),
262 ],
263 },
264 OpSpec {
265 name: "owner_history",
266 camel: "ownerHistory",
267 fields: &[
268 field("person_identification", "personIdentification", K::Text),
269 field("family_name", "familyName", K::Text),
270 field("given_name", "givenName", K::Text),
271 required("organization", "organization", K::Text),
272 required("application_name", "applicationName", K::Text),
273 required("application_version", "applicationVersion", K::Text),
274 required("application_identifier", "applicationIdentifier", K::Text),
275 field("change_action", "changeAction", K::Text),
276 required("creation_date", "creationDate", K::Integer),
277 field("last_modified_date", "lastModifiedDate", K::Integer),
278 ],
279 },
280];
281
282pub fn op_spec(name: &str) -> Option<&'static OpSpec> {
284 OPS.iter()
285 .find(|op| op.name.eq_ignore_ascii_case(name) || op.camel.eq_ignore_ascii_case(name))
286}
287
288#[derive(Debug, Clone)]
291#[cfg_attr(not(feature = "author"), allow(dead_code))]
292pub(crate) enum Arg {
293 Text(String),
294 Id(u64),
295 Ids(Vec<u64>),
296 Reals([f64; 3]),
297 Integer(i64),
298 Bool(bool),
299 Texts(Vec<String>),
300 Attributes(Vec<(String, Tagged)>),
301}
302
303#[cfg_attr(not(feature = "author"), allow(dead_code))]
305pub(crate) struct Fields {
306 pub(crate) spec: &'static OpSpec,
307 pub(crate) args: Vec<(&'static str, Arg)>,
308}
309
310#[cfg_attr(not(feature = "author"), allow(dead_code))]
311impl Fields {
312 pub(crate) fn take(&mut self, name: &str) -> Option<Arg> {
313 let index = self.args.iter().position(|(key, _)| *key == name)?;
314 Some(self.args.remove(index).1)
315 }
316}
317
318pub(crate) fn invalid(detail: impl Into<String>) -> BindingError {
319 BindingError::InvalidValue(detail.into())
320}
321
322pub(crate) fn read(value: &Tagged) -> Result<Fields, BindingError> {
324 let Tagged::List(items) = value else {
325 return Err(invalid("an operation is a LIST"));
326 };
327 let Some(Tagged::Enum(name)) = items.first() else {
328 return Err(invalid("an operation starts with an ENUM naming it"));
329 };
330 let spec = op_spec(name).ok_or_else(|| {
331 let known: Vec<&str> = OPS.iter().map(|op| op.name).collect();
332 invalid(format!(
333 "no operation `{name}`; known: {}",
334 known.join(", ")
335 ))
336 })?;
337 let rest = &items[1..];
338 if rest.len() % 2 != 0 {
339 return Err(invalid(format!(
340 "`{}` takes alternating field names and values",
341 spec.name
342 )));
343 }
344 let mut args: Vec<(&'static str, Arg)> = Vec::new();
345 for pair in rest.chunks(2) {
346 let Tagged::Text(key) = &pair[0] else {
347 return Err(invalid(format!("`{}` field names are TEXT", spec.name)));
348 };
349 let field = spec.field(key).ok_or_else(|| {
350 let known: Vec<&str> = spec.fields.iter().map(|f| f.name).collect();
351 invalid(format!(
352 "`{}` has no field `{key}`; it takes {}",
353 spec.name,
354 known.join(", ")
355 ))
356 })?;
357 if args.iter().any(|(name, _)| *name == field.name) {
358 return Err(invalid(format!(
359 "`{}.{}` is given twice",
360 spec.name, field.name
361 )));
362 }
363 if matches!(pair[1], Tagged::Null) {
364 continue;
365 }
366 let arg = arg(field.kind, &pair[1])
367 .map_err(|detail| invalid(format!("`{}.{}` {detail}", spec.name, field.name)))?;
368 args.push((field.name, arg));
369 }
370 for field in spec.fields.iter().filter(|f| f.required) {
371 if !args.iter().any(|(name, _)| *name == field.name) {
372 return Err(invalid(format!("`{}` needs `{}`", spec.name, field.name)));
373 }
374 }
375 Ok(Fields { spec, args })
376}
377
378fn arg(kind: FieldKind, value: &Tagged) -> Result<Arg, String> {
379 Ok(match kind {
380 K::Text => match value {
381 Tagged::Text(text) => Arg::Text(text.clone()),
382 _ => return Err("must be TEXT".into()),
383 },
384 K::Id => Arg::Id(id(value)?),
385 K::Ids => match value {
386 Tagged::List(items) => Arg::Ids(items.iter().map(id).collect::<Result<_, _>>()?),
387 _ => return Err("must be a LIST of ids".into()),
388 },
389 K::Reals => {
390 let Tagged::List(items) = value else {
391 return Err("must be a LIST of three numbers".into());
392 };
393 let numbers: Vec<f64> = items
394 .iter()
395 .map(|item| match item {
396 #[allow(clippy::cast_precision_loss)]
397 Tagged::Integer(i) => Ok(*i as f64),
398 Tagged::Real(r) if r.is_finite() => Ok(*r),
399 _ => Err("must hold finite numbers".to_owned()),
400 })
401 .collect::<Result<_, _>>()?;
402 Arg::Reals(
403 numbers
404 .try_into()
405 .map_err(|_| "must hold exactly three numbers".to_owned())?,
406 )
407 }
408 K::Integer => match value {
409 Tagged::Integer(i) => Arg::Integer(*i),
410 _ => return Err("must be an INTEGER".into()),
411 },
412 K::Bool => match value {
413 Tagged::Bool(b) => Arg::Bool(*b),
414 _ => return Err("must be a BOOL".into()),
415 },
416 K::Texts => match value {
417 Tagged::List(items) => Arg::Texts(
418 items
419 .iter()
420 .map(|item| match item {
421 Tagged::Text(text) => Ok(text.clone()),
422 _ => Err("must be a LIST of TEXT".to_owned()),
423 })
424 .collect::<Result<_, _>>()?,
425 ),
426 _ => return Err("must be a LIST of TEXT".into()),
427 },
428 K::Attributes => {
429 let Tagged::List(items) = value else {
430 return Err("must be a LIST of (name, value) pairs".into());
431 };
432 Arg::Attributes(
433 items
434 .iter()
435 .map(|item| match item {
436 Tagged::List(pair) => match pair.as_slice() {
437 [Tagged::Text(name), value] => Ok((name.clone(), value.clone())),
438 _ => Err("holds a pair that is not (TEXT name, value)".to_owned()),
439 },
440 _ => Err("holds an item that is not a (name, value) LIST".to_owned()),
441 })
442 .collect::<Result<_, _>>()?,
443 )
444 }
445 })
446}
447
448fn id(value: &Tagged) -> Result<u64, String> {
449 match value {
450 Tagged::Ref(id) => Ok(*id),
451 Tagged::Integer(id) => u64::try_from(*id).map_err(|_| format!("id {id} is negative")),
452 _ => Err("must be an id (REF or INTEGER)".into()),
453 }
454}