Skip to main content

openbim_ifc_binding_core/
properties.rs

1//! Property sets, quantities and units (feature `properties`, #123).
2//!
3//! The facade's exact, release-bound resolver (`ifc::properties::
4//! exact_properties`) answers for one object: its own sets, then the sets
5//! its type object holds, an occurrence property overriding an inherited
6//! one of the same set and name. Each set and property crosses as an owned
7//! record keyed by entity id, with the set's `GlobalId`. Values keep their
8//! declared IFC type in the tagged encoding: a quantity's bare `2.5` read
9//! as `IfcLengthMeasure` crosses as `typed IFCLENGTHMEASURE(real 2.5)`, a
10//! label as `typed IFCLABEL(text ...)`, and `.U.` stays `unknown`.
11//!
12//! The release is the one the header declares, IFC2X3, IFC4 or IFC4X3;
13//! any other is refused with `unsupported-schema`, and a model read
14//! leniently with skipped records with `invalid-model`, since an exact
15//! answer cannot be proven from an incomplete file.
16//!
17//! # Many objects in one call (#358)
18//!
19//! [`IfcModel::property_sets`] validates every `IfcRelDefinesByProperties`
20//! and `IfcRelDefinesByType` of the file on each call, because a malformed
21//! one could hide an assignment; a host loop over every object is then
22//! quadratic. [`IfcModel::property_sets_many`] builds one
23//! `ifc::properties::PropertyIndex` for the call, so the validation runs
24//! once and the whole pass is linear in objects plus relationships. Its
25//! answer for each object is exactly the per-object call's: the same sets,
26//! or the same refusal, as an [`ObjectPropertySets`] record.
27//!
28//! The index never outlives the call. It borrows the model, which the
29//! binding owns and mutates through `&mut self`, so no index can be held
30//! across an edit and no answer can come from a model state other than
31//! the one the call sees: there is no cache to invalidate. The per-object
32//! call keeps the free resolver for the same reason; to resolve many
33//! objects, ask for them together.
34//!
35//! The records are shaped for the checked edit of part 2 of #123: a
36//! property is addressed by its object, set name and property name, and its
37//! `value` is exactly the tagged value an edit would write back.
38
39use crate::record::{Field, Record, ToRecord};
40use crate::value::Tagged;
41use crate::{BindingError, IfcModel};
42
43/// One property set, quantity set or predefined property set applying to
44/// an object.
45#[derive(Debug, Clone, PartialEq)]
46pub struct PropertySet {
47    /// The set's entity id.
48    pub id: u64,
49    /// The set's `GlobalId`.
50    pub global_id: Option<String>,
51    /// The set's `Name`; a predefined set that states none is named by its
52    /// entity (`IfcDoorLiningProperties`).
53    pub name: String,
54    /// The set's entity type, upper-case: `IFCPROPERTYSET`,
55    /// `IFCELEMENTQUANTITY`, or a predefined set such as
56    /// `IFCDOORLININGPROPERTIES`.
57    pub type_name: String,
58    /// `occurrence`: stated on the queried object; `type`: held by a type
59    /// object's `HasPropertySets` (inherited, or the queried type's own).
60    pub source: String,
61    /// For `type`, the type object's id.
62    pub source_id: Option<u64>,
63    /// The set's properties and quantities, in file order. An inherited
64    /// property overridden by the occurrence is left out.
65    pub properties: Vec<Property>,
66}
67
68/// One property, quantity or predefined-set attribute.
69#[derive(Debug, Clone, PartialEq)]
70pub struct Property {
71    /// The property or quantity entity; for a predefined set's attribute,
72    /// which is no entity, the set's id.
73    pub id: u64,
74    /// `Name`, or the attribute name of a predefined set.
75    pub name: String,
76    /// The entity type of [`Self::id`], upper-case:
77    /// `IFCPROPERTYSINGLEVALUE`, `IFCQUANTITYLENGTH`, ...
78    pub type_name: String,
79    /// The value form: `value` (one value, `null` when unset), `enumerated`,
80    /// `list`, `bounded`, `table`, `reference` or `complex`.
81    pub kind: String,
82    /// The declared IFC value type (`IFCLENGTHMEASURE`), when there is one.
83    pub value_type: Option<String>,
84    /// The unit entity the property states (`Unit`); `None` when the
85    /// project default applies or no unit does. Resolve either with
86    /// [`IfcModel::resolve_unit`].
87    pub unit: Option<u64>,
88    /// `value`: the value, typed. `enumerated`: the selected values as a
89    /// `list`. `list`: the values as a `list`. `reference`: the target as a
90    /// `ref`, or `null`. `bounded`, `table`, `complex`: `null`, see the
91    /// fields below.
92    pub value: Tagged,
93    /// `enumerated`: the `IfcPropertyEnumeration` the values come from.
94    pub enumeration: Option<Enumeration>,
95    /// `bounded`: the bounds and set point.
96    pub bounds: Option<Bounds>,
97    /// `table`: the rows and units.
98    pub table: Option<Table>,
99    /// `reference`: `UsageName`; `complex`: `UsageName` or `Usage`.
100    pub usage: Option<String>,
101    /// `complex` quantity: `Discrimination`.
102    pub discrimination: Option<String>,
103    /// `complex` quantity: `Quality`.
104    pub quality: Option<String>,
105    /// `complex`: its members, each resolved as a property.
106    pub members: Vec<Property>,
107}
108
109/// The answer for one object of [`IfcModel::property_sets_many`]: its
110/// sets, or why the per-object call would refuse it.
111#[derive(Debug, Clone, PartialEq)]
112pub struct ObjectPropertySets {
113    /// The object's entity id.
114    pub object: u64,
115    /// Its sets, as [`IfcModel::property_sets`] returns them; empty when
116    /// refused.
117    pub sets: Vec<PropertySet>,
118    /// The refusal [`IfcModel::property_sets`] would return for it.
119    pub refusal: Option<PropertyRefusal>,
120}
121
122/// Why one object's property sets were refused: the shared binding code
123/// and message of the error the per-object call returns.
124#[derive(Debug, Clone, PartialEq, Eq)]
125pub struct PropertyRefusal {
126    /// The binding error code: `missing-entity`, `wrong-entity-type`,
127    /// `invalid-model`, `missing-reference`, `budget-exceeded`,
128    /// `unsupported`, ...
129    pub code: String,
130    /// The error's message.
131    pub message: String,
132}
133
134impl From<&BindingError> for PropertyRefusal {
135    fn from(error: &BindingError) -> Self {
136        Self {
137            code: error.code().to_owned(),
138            message: error.to_string(),
139        }
140    }
141}
142
143/// An `IfcPropertyEnumeration`.
144#[derive(Debug, Clone, PartialEq)]
145pub struct Enumeration {
146    /// Its entity id.
147    pub id: u64,
148    /// Its `Name`.
149    pub name: String,
150    /// The permitted values, typed.
151    pub values: Vec<Tagged>,
152}
153
154/// The values of an `IfcPropertyBoundedValue`; `null` when unstated.
155#[derive(Debug, Clone, PartialEq)]
156pub struct Bounds {
157    /// `LowerBoundValue`.
158    pub lower: Tagged,
159    /// `UpperBoundValue`.
160    pub upper: Tagged,
161    /// `SetPointValue` (IFC4, IFC4X3).
162    pub set_point: Tagged,
163}
164
165/// An `IfcPropertyTableValue`.
166#[derive(Debug, Clone, PartialEq)]
167pub struct Table {
168    /// `(defining, defined)` value pairs, typed, in file order.
169    pub rows: Vec<(Tagged, Tagged)>,
170    /// `Expression`.
171    pub expression: Option<String>,
172    /// `DefiningUnit`.
173    pub defining_unit: Option<u64>,
174    /// `DefinedUnit`.
175    pub defined_unit: Option<u64>,
176    /// `CurveInterpolation` (IFC4, IFC4X3), e.g. `LINEAR`.
177    pub interpolation: Option<String>,
178}
179
180/// A measure's effective unit, resolved to SI: `si = value * scale +
181/// offset`.
182#[derive(Debug, Clone, PartialEq)]
183pub struct ResolvedUnit {
184    /// The unit entity that applies; `None` for a dimensionless measure.
185    pub unit: Option<u64>,
186    /// Whether `unit` is the project default rather than the stated one.
187    pub from_project: bool,
188    /// SI dimensional exponents `[L, M, T, I, Θ, N, J]`.
189    pub dimensions: [i32; 7],
190    /// Multiplier into the SI base unit.
191    pub scale: f64,
192    /// Added after scaling; nonzero only for degrees Celsius.
193    pub offset: f64,
194}
195
196impl IfcModel {
197    /// Every property set, quantity set and predefined property set that
198    /// applies to `object`, with their properties, resolved exactly.
199    ///
200    /// Occurrence sets come first, then the sets inherited from the
201    /// object's type, each in assignment order. `object` may be a type
202    /// object, which reads its own `HasPropertySets`. Refused with
203    /// `missing-entity` for an id not in the model, `wrong-entity-type` for
204    /// an entity that carries no property sets, `unsupported-schema` for a
205    /// release other than IFC2X3, IFC4 or IFC4X3, `invalid-model` when the
206    /// file's sets are malformed or ambiguous, and `feature-disabled`
207    /// without the `properties` feature.
208    pub fn property_sets(&self, object: u64) -> Result<Vec<PropertySet>, BindingError> {
209        #[cfg(feature = "properties")]
210        {
211            read::property_sets(self, object)
212        }
213        #[cfg(not(feature = "properties"))]
214        {
215            let _ = object;
216            Err(BindingError::FeatureDisabled("properties"))
217        }
218    }
219
220    /// [`Self::property_sets`] of each of `objects`, in the order given,
221    /// or, with `None`, of every object definition (`IfcObjectDefinition`
222    /// and its subtypes: objects and type objects) in file order, resolved
223    /// through one property index in time linear in objects plus
224    /// relationships (#358).
225    ///
226    /// Each record holds exactly what the per-object call answers: its
227    /// sets, or its refusal (`missing-entity`, `wrong-entity-type`,
228    /// `invalid-model`, ...) as code and message. Refused as a whole only
229    /// when the model is: `unsupported-schema` for a release other than
230    /// IFC2X3, IFC4 or IFC4X3, `invalid-model` for a lenient read with
231    /// skipped records, and `feature-disabled` without the `properties`
232    /// feature.
233    pub fn property_sets_many(
234        &self,
235        objects: Option<&[u64]>,
236    ) -> Result<Vec<ObjectPropertySets>, BindingError> {
237        #[cfg(feature = "properties")]
238        {
239            read::property_sets_many(self, objects)
240        }
241        #[cfg(not(feature = "properties"))]
242        {
243            let _ = objects;
244            Err(BindingError::FeatureDisabled("properties"))
245        }
246    }
247
248    /// The effective unit of a value of `measure_type` (`IFCAREAMEASURE`):
249    /// `unit` when given (a property's stated unit), otherwise the project
250    /// default for that measure, resolved exactly to SI.
251    ///
252    /// Refused with `invalid-value` for a type that is no measure,
253    /// `unsupported` for a measure with no verified SI correspondence (a
254    /// monetary one) or an offset unit, `invalid-model` for a missing,
255    /// duplicated or malformed unit, and `feature-disabled` without the
256    /// `properties` feature.
257    pub fn resolve_unit(
258        &self,
259        measure_type: &str,
260        unit: Option<u64>,
261    ) -> Result<ResolvedUnit, BindingError> {
262        #[cfg(feature = "properties")]
263        {
264            read::resolve_unit(self, measure_type, unit)
265        }
266        #[cfg(not(feature = "properties"))]
267        {
268            let _ = (measure_type, unit);
269            Err(BindingError::FeatureDisabled("properties"))
270        }
271    }
272}
273
274impl ToRecord for PropertySet {
275    fn to_record(&self) -> Record {
276        Record::new(
277            "PropertySet",
278            vec![
279                ("id", Field::Id(self.id)),
280                ("global_id", Field::text(self.global_id.clone())),
281                ("name", Field::Text(self.name.clone())),
282                ("type_name", Field::Text(self.type_name.clone())),
283                ("source", Field::Text(self.source.clone())),
284                ("source_id", Field::id(self.source_id)),
285                ("properties", Field::records(&self.properties)),
286            ],
287        )
288    }
289}
290
291impl ToRecord for ObjectPropertySets {
292    fn to_record(&self) -> Record {
293        Record::new(
294            "ObjectPropertySets",
295            vec![
296                ("object", Field::Id(self.object)),
297                ("sets", Field::records(&self.sets)),
298                ("refusal", Field::record(self.refusal.as_ref())),
299            ],
300        )
301    }
302}
303
304impl ToRecord for PropertyRefusal {
305    fn to_record(&self) -> Record {
306        Record::new(
307            "PropertyRefusal",
308            vec![
309                ("code", Field::Text(self.code.clone())),
310                ("message", Field::Text(self.message.clone())),
311            ],
312        )
313    }
314}
315
316impl ToRecord for Property {
317    fn to_record(&self) -> Record {
318        Record::new(
319            "Property",
320            vec![
321                ("id", Field::Id(self.id)),
322                ("name", Field::Text(self.name.clone())),
323                ("type_name", Field::Text(self.type_name.clone())),
324                ("kind", Field::Text(self.kind.clone())),
325                ("value_type", Field::text(self.value_type.clone())),
326                ("unit", Field::id(self.unit)),
327                ("value", Field::Value(self.value.clone())),
328                ("enumeration", Field::record(self.enumeration.as_ref())),
329                ("bounds", Field::record(self.bounds.as_ref())),
330                ("table", Field::record(self.table.as_ref())),
331                ("usage", Field::text(self.usage.clone())),
332                ("discrimination", Field::text(self.discrimination.clone())),
333                ("quality", Field::text(self.quality.clone())),
334                ("members", Field::records(&self.members)),
335            ],
336        )
337    }
338}
339
340impl ToRecord for Enumeration {
341    fn to_record(&self) -> Record {
342        Record::new(
343            "PropertyEnumeration",
344            vec![
345                ("id", Field::Id(self.id)),
346                ("name", Field::Text(self.name.clone())),
347                (
348                    "values",
349                    Field::List(self.values.iter().cloned().map(Field::Value).collect()),
350                ),
351            ],
352        )
353    }
354}
355
356impl ToRecord for Bounds {
357    fn to_record(&self) -> Record {
358        Record::new(
359            "PropertyBounds",
360            vec![
361                ("lower", Field::Value(self.lower.clone())),
362                ("upper", Field::Value(self.upper.clone())),
363                ("set_point", Field::Value(self.set_point.clone())),
364            ],
365        )
366    }
367}
368
369impl ToRecord for Table {
370    fn to_record(&self) -> Record {
371        let rows = self
372            .rows
373            .iter()
374            .map(|(defining, defined)| {
375                Field::Record(Record::new(
376                    "PropertyTableRow",
377                    vec![
378                        ("defining", Field::Value(defining.clone())),
379                        ("defined", Field::Value(defined.clone())),
380                    ],
381                ))
382            })
383            .collect();
384        Record::new(
385            "PropertyTable",
386            vec![
387                ("rows", Field::List(rows)),
388                ("expression", Field::text(self.expression.clone())),
389                ("defining_unit", Field::id(self.defining_unit)),
390                ("defined_unit", Field::id(self.defined_unit)),
391                ("interpolation", Field::text(self.interpolation.clone())),
392            ],
393        )
394    }
395}
396
397impl ToRecord for ResolvedUnit {
398    fn to_record(&self) -> Record {
399        Record::new(
400            "ResolvedUnit",
401            vec![
402                ("unit", Field::id(self.unit)),
403                ("from_project", Field::Bool(self.from_project)),
404                (
405                    "dimensions",
406                    Field::List(
407                        self.dimensions
408                            .iter()
409                            .map(|exponent| Field::Int(i64::from(*exponent)))
410                            .collect(),
411                    ),
412                ),
413                ("scale", Field::Real(self.scale)),
414                ("offset", Field::Real(self.offset)),
415            ],
416        )
417    }
418}
419
420#[cfg(feature = "properties")]
421pub(crate) mod read {
422    use ifc::properties::{
423        exact_properties, exact_unit, ExactComplexMember, ExactLogical, ExactProperty,
424        ExactPropertyEntry, ExactPropertyError, ExactSource, ExactTypedValue, ExactUnitError,
425        ExactValue, PropertyIndex,
426    };
427    use ifc::EntityId;
428
429    use super::{
430        Bounds, Enumeration, ObjectPropertySets, Property, PropertyRefusal, PropertySet,
431        ResolvedUnit, Table,
432    };
433    use crate::value::Tagged;
434    use crate::{BindingError, IfcModel};
435
436    pub(super) fn property_sets(
437        model: &IfcModel,
438        object: u64,
439    ) -> Result<Vec<PropertySet>, BindingError> {
440        sets_of(model, object, |id| exact_properties(&model.inner, id))
441    }
442
443    pub(super) fn property_sets_many(
444        model: &IfcModel,
445        objects: Option<&[u64]>,
446    ) -> Result<Vec<ObjectPropertySets>, BindingError> {
447        let index = PropertyIndex::build(&model.inner);
448        // A refusal of the whole model is every object's answer; say it
449        // once.
450        index.schema().map_err(property_error)?;
451        let every;
452        let objects = match objects {
453            Some(objects) => objects,
454            None => {
455                every = model.ids_of_type_including_subtypes("IfcObjectDefinition")?;
456                &every
457            }
458        };
459        Ok(objects
460            .iter()
461            .map(
462                |&object| match sets_of(model, object, |id| index.exact_properties(id)) {
463                    Ok(sets) => ObjectPropertySets {
464                        object,
465                        sets,
466                        refusal: None,
467                    },
468                    Err(error) => ObjectPropertySets {
469                        object,
470                        sets: Vec::new(),
471                        refusal: Some(PropertyRefusal::from(&error)),
472                    },
473                },
474            )
475            .collect())
476    }
477
478    /// One object's sets, from the exact entries `resolve` gives: the free
479    /// resolver or an index, which answer alike.
480    fn sets_of(
481        model: &IfcModel,
482        object: u64,
483        resolve: impl FnOnce(EntityId) -> Result<Vec<ExactPropertyEntry>, ExactPropertyError>,
484    ) -> Result<Vec<PropertySet>, BindingError> {
485        if !model.inner.contains(EntityId(object)) {
486            return Err(BindingError::MissingEntity(object));
487        }
488        let entries = resolve(EntityId(object)).map_err(property_error)?;
489        let mut sets: Vec<PropertySet> = Vec::new();
490        for entry in entries {
491            let property = &entry.property;
492            let (source, source_id) = source(property.source);
493            let set_id = property.set_id.0;
494            let record = convert(model, &entry.name, property.property_id.0, property)?;
495            match sets
496                .iter_mut()
497                .find(|set| set.id == set_id && set.source_id == source_id)
498            {
499                Some(set) => set.properties.push(record),
500                None => {
501                    let identity = model.identity(set_id)?;
502                    sets.push(PropertySet {
503                        id: set_id,
504                        global_id: identity.global_id,
505                        name: property.property_set.to_string(),
506                        type_name: model.type_of(set_id)?.to_owned(),
507                        source: source.to_owned(),
508                        source_id,
509                        properties: vec![record],
510                    });
511                }
512            }
513        }
514        Ok(sets)
515    }
516
517    pub(super) fn resolve_unit(
518        model: &IfcModel,
519        measure_type: &str,
520        unit: Option<u64>,
521    ) -> Result<ResolvedUnit, BindingError> {
522        let resolved =
523            exact_unit(&model.inner, measure_type, unit.map(EntityId)).map_err(unit_error)?;
524        Ok(ResolvedUnit {
525            unit: resolved.unit.map(|EntityId(id)| id),
526            from_project: resolved.from_project,
527            dimensions: resolved.dimensions,
528            scale: resolved.scale,
529            offset: resolved.offset,
530        })
531    }
532
533    fn source(source: ExactSource) -> (&'static str, Option<u64>) {
534        match source {
535            ExactSource::Occurrence => ("occurrence", None),
536            ExactSource::Type(id) => ("type", Some(id.0)),
537            ExactSource::Material(id) => ("material", Some(id.0)),
538            // A provenance added after this binding still names its holder
539            // nowhere; say so rather than guess.
540            _ => ("other", None),
541        }
542    }
543
544    fn convert(
545        model: &IfcModel,
546        name: &str,
547        id: u64,
548        property: &ExactProperty,
549    ) -> Result<Property, BindingError> {
550        member(
551            model,
552            name,
553            id,
554            property.value_type.as_deref(),
555            property.unit_id.map(|EntityId(id)| id),
556            &property.value,
557        )
558    }
559
560    fn member(
561        model: &IfcModel,
562        name: &str,
563        id: u64,
564        value_type: Option<&str>,
565        unit: Option<u64>,
566        value: &ExactValue,
567    ) -> Result<Property, BindingError> {
568        let mut property = Property {
569            id,
570            name: name.to_owned(),
571            type_name: model.type_of(id)?.to_owned(),
572            kind: "value".to_owned(),
573            value_type: value_type.map(str::to_owned),
574            unit,
575            value: Tagged::Null,
576            enumeration: None,
577            bounds: None,
578            table: None,
579            usage: None,
580            discrimination: None,
581            quality: None,
582            members: Vec::new(),
583        };
584        match value {
585            ExactValue::Enumerated(enumerated) => {
586                property.kind = "enumerated".to_owned();
587                property.value = Tagged::List(typed_all(&enumerated.values)?);
588                property.enumeration = enumerated
589                    .enumeration
590                    .as_ref()
591                    .map(|e| -> Result<_, BindingError> {
592                        Ok(Enumeration {
593                            id: e.id.0,
594                            name: e.name.to_string(),
595                            values: typed_all(&e.values)?,
596                        })
597                    })
598                    .transpose()?;
599            }
600            ExactValue::List(values) => {
601                property.kind = "list".to_owned();
602                property.value = Tagged::List(typed_all(values)?);
603            }
604            ExactValue::Bounded(bounded) => {
605                property.kind = "bounded".to_owned();
606                let bound = |value: &Option<ExactTypedValue>| {
607                    value.as_ref().map_or(Ok(Tagged::Null), typed)
608                };
609                property.bounds = Some(Bounds {
610                    lower: bound(&bounded.lower)?,
611                    upper: bound(&bounded.upper)?,
612                    set_point: bound(&bounded.set_point)?,
613                });
614            }
615            ExactValue::Table(table) => {
616                property.kind = "table".to_owned();
617                property.table = Some(Table {
618                    rows: table
619                        .rows
620                        .iter()
621                        .map(|row| Ok((typed(&row.defining)?, typed(&row.defined)?)))
622                        .collect::<Result<_, BindingError>>()?,
623                    expression: table.expression.as_deref().map(str::to_owned),
624                    defining_unit: table.defining_unit.map(|EntityId(id)| id),
625                    defined_unit: table.defined_unit.map(|EntityId(id)| id),
626                    interpolation: table.interpolation.as_deref().map(str::to_owned),
627                });
628            }
629            ExactValue::Reference(reference) => {
630                property.kind = "reference".to_owned();
631                property.usage = reference.usage_name.as_deref().map(str::to_owned);
632                property.value = reference
633                    .target
634                    .as_ref()
635                    .map_or(Tagged::Null, |target| Tagged::Ref(target.id.0));
636            }
637            ExactValue::Complex(complex) => {
638                property.kind = "complex".to_owned();
639                property.usage = complex.usage.as_deref().map(str::to_owned);
640                property.discrimination = complex.discrimination.as_deref().map(str::to_owned);
641                property.quality = complex.quality.as_deref().map(str::to_owned);
642                property.members = complex
643                    .members
644                    .iter()
645                    .map(|m: &ExactComplexMember| {
646                        member(
647                            model,
648                            &m.name,
649                            m.id.0,
650                            m.value_type.as_deref(),
651                            m.unit_id.map(|EntityId(id)| id),
652                            &m.value,
653                        )
654                    })
655                    .collect::<Result<_, _>>()?;
656            }
657            scalar => {
658                let payload = scalar_value(scalar)?;
659                property.value = match (value_type, payload) {
660                    // An unset value, an enumeration constant and an entity
661                    // are never wrapped: `value_type` still names their
662                    // declared type.
663                    (_, payload @ (Tagged::Null | Tagged::Enum(_) | Tagged::Ref(_))) => payload,
664                    (Some(value_type), payload) => Tagged::Typed {
665                        type_name: value_type.to_owned(),
666                        value: Box::new(payload),
667                    },
668                    (None, payload) => payload,
669                };
670            }
671        }
672        Ok(property)
673    }
674
675    /// A typed member of a list, bound, table or enumeration: a scalar by
676    /// the resolver's contract, refused with `unsupported` otherwise rather
677    /// than replaced.
678    fn typed(value: &ExactTypedValue) -> Result<Tagged, BindingError> {
679        Ok(Tagged::Typed {
680            type_name: value.value_type.to_string(),
681            value: Box::new(scalar_value(&value.value)?),
682        })
683    }
684
685    fn typed_all(values: &[ExactTypedValue]) -> Result<Vec<Tagged>, BindingError> {
686        values.iter().map(typed).collect()
687    }
688
689    /// The tagged payload of a scalar exact value.
690    fn scalar_value(value: &ExactValue) -> Result<Tagged, BindingError> {
691        Ok(match value {
692            ExactValue::Null => Tagged::Null,
693            ExactValue::Bool(value) => Tagged::Bool(*value),
694            ExactValue::Logical(ExactLogical::True) => Tagged::Bool(true),
695            ExactValue::Logical(ExactLogical::False) => Tagged::Bool(false),
696            ExactValue::Logical(ExactLogical::Unknown) => Tagged::Unknown,
697            ExactValue::Binary(digits) => Tagged::Binary(digits.to_string()),
698            ExactValue::Integer(value) => Tagged::Integer(*value),
699            ExactValue::Real(value) => Tagged::Real(*value),
700            ExactValue::Text(text) => Tagged::Text(text.to_string()),
701            ExactValue::Enum(token) => Tagged::Enum(token.to_string()),
702            ExactValue::Entity(entity) => Tagged::Ref(entity.id.0),
703            other => {
704                return Err(BindingError::Unsupported(format!(
705                    "a property value form this binding does not carry: {other:?}"
706                )))
707            }
708        })
709    }
710
711    pub(crate) fn property_error(error: ExactPropertyError) -> BindingError {
712        use ExactPropertyError as E;
713        let detail = error.to_string();
714        match error {
715            E::MissingSchema => BindingError::UnsupportedSchema(String::new()),
716            E::UnsupportedSchema { schema } => BindingError::UnsupportedSchema(schema),
717            E::MultipleSchemas { .. } => BindingError::UnsupportedSchema(detail),
718            E::MissingReference { .. } => BindingError::MissingReference(detail),
719            E::InvalidQueryObject { .. } => BindingError::WrongEntityType(detail),
720            E::ComplexCycle { .. } | E::ComplexTooDeep { .. } | E::ComplexBudgetExceeded { .. } => {
721                BindingError::BudgetExceeded(detail)
722            }
723            E::UnsupportedDefinition { .. }
724            | E::UnsupportedProperty { .. }
725            | E::UnsupportedRelationship { .. }
726            | E::UnsupportedUnit { .. } => BindingError::Unsupported(detail),
727            _ => BindingError::InvalidModel(detail),
728        }
729    }
730
731    pub(crate) fn unit_error(error: ExactUnitError) -> BindingError {
732        use ExactUnitError as E;
733        let detail = error.to_string();
734        match error {
735            E::Structure(error) => property_error(error),
736            E::MeasureNotInSchema { .. } | E::NotAMeasure { .. } => {
737                BindingError::InvalidValue(detail)
738            }
739            E::UnmappedMeasureType { .. }
740            | E::UnsupportedUnit { .. }
741            | E::UnsupportedOffset { .. } => BindingError::Unsupported(detail),
742            E::CyclicConversion { .. } | E::ConversionChainTooDeep { .. } => {
743                BindingError::BudgetExceeded(detail)
744            }
745            _ => BindingError::InvalidModel(detail),
746        }
747    }
748}