ifc_lite_processing/data_model/render/
flat.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! The flat encoder: `AttributeValue` and decoded property rows into the
6//! `PropValue` / `PropertySet` shape CSV, JSON, JSON-LD, IFCX, USD, BOS and
7//! the Python binding read (D41). The other encoder is `render::columnar`.
8//!
9//! Moved from `rust/export/src/model_props.rs` (C6-8, #7783).
10
11use super::super::property::{PropertyDecoder, PropertyKind, PropertyRow, PropertyScope};
12use super::super::quantity::decode_quantity_set;
13use super::super::rows::{PropValue, PropertySet, QuantitySet, ValueKind};
14use std::collections::HashSet;
15
16use ifc_lite_core::{slot, AttributeValue, DecodedEntity, EntityDecoder, IfcType};
17
18pub use ifc_lite_core::fmt_num::fmt_num;
19
20/// Map an IFC boolean/logical enum token to a friendly string.
21pub fn map_enum(e: &str) -> String {
22    match e {
23        "T" => "true".to_string(),
24        "F" => "false".to_string(),
25        "U" => "unknown".to_string(),
26        other => other.to_string(),
27    }
28}
29
30/// A property value rendered for the flat exports.
31pub struct Rendered {
32    pub value: String,
33    pub value_type: String,
34    pub kind: ValueKind,
35}
36
37/// Render an `AttributeValue` (single property value) to its display string,
38/// type tag and primitive kind. Typed values like `IFCLABEL('x')` decode to
39/// [`AttributeValue::Typed`]; the kind comes from its value. A list is not a
40/// single value and renders nothing (it used to render its second item under
41/// its first item's name when the first was a string, F3c).
42pub fn render_value(v: &AttributeValue) -> Option<Rendered> {
43    let rendered = |value: String, tag: &str, kind| Rendered { value, value_type: tag.to_string(), kind };
44    match v {
45        AttributeValue::String(s) | AttributeValue::Binary(s) => Some(rendered(s.clone(), "IFCTEXT", ValueKind::Text)),
46        AttributeValue::Integer(i) => Some(rendered(i.to_string(), "IFCINTEGER", ValueKind::Number)),
47        AttributeValue::Float(f) => Some(rendered(fmt_num(*f), "IFCREAL", ValueKind::Number)),
48        AttributeValue::Enum(e) => {
49            let kind = if matches!(e.as_str(), "T" | "F") { ValueKind::Bool } else { ValueKind::Text };
50            Some(rendered(map_enum(e), "IFCBOOLEAN", kind))
51        }
52        AttributeValue::Typed { name, value } => {
53            let inner = render_value(value)?;
54            Some(Rendered { value_type: name.to_string(), ..inner })
55        }
56        // Entity-ref-valued properties (rare for NominalValue) aren't rendered inline.
57        AttributeValue::List(_)
58        | AttributeValue::EntityRef(_)
59        | AttributeValue::Null
60        | AttributeValue::Derived => None,
61    }
62}
63
64/// Attribute names every rooted entity carries, which the row already surfaces
65/// as dedicated fields or which are references the flattened export cannot
66/// render. Skipped so `attributes` holds only what the entity class adds.
67const COMMON_ATTRIBUTES: [&str; 7] = [
68    "GlobalId",
69    "OwnerHistory",
70    "Name",
71    "Description",
72    "ObjectType",
73    "ObjectPlacement",
74    "Representation",
75];
76
77/// Render the attributes an entity's own IFC class declares, by schema name.
78///
79/// These are not property sets and no `IfcRelDefinesByProperties` points at
80/// them: `IfcReinforcingBar.NominalDiameter`, `IfcDoor.OverallHeight` and their
81/// like are declared directly on the entity, so a consumer reading only psets
82/// cannot see them however inheritance is configured.
83///
84/// `raw_type_name` is the STEP keyword as written in the file (e.g.
85/// `"IFCDOORSTYLE"`). Its source-schema registry, rather than the merged
86/// canonical universe, determines its positional attribute names. Unknown
87/// source schemas and entities emit no names rather than borrowing another
88/// version's layout.
89///
90/// Values reuse [`render_value`], so a rendered attribute reads the same as a
91/// property with the same underlying type, and anything it declines (entity
92/// references, `$`, derived `*`) is omitted rather than emitted as a dangling
93/// `#123`. Order follows the schema's attribute order, which is stable.
94pub fn render_attributes(
95    entity: &DecodedEntity, raw_type_name: &str, source_schema: Option<&str>,
96) -> Vec<PropValue> {
97    let names: &[&str] = source_schema
98        .and_then(|schema| ifc_lite_core::attribute_names_for_schema(schema, raw_type_name))
99        .unwrap_or(&[]);
100    let mut out = Vec::new();
101    for (i, name) in names.iter().enumerate() {
102        if COMMON_ATTRIBUTES.contains(name) {
103            continue;
104        }
105        let Some(v) = entity.get(i) else { continue };
106        if let Some(Rendered { value, mut value_type, kind }) = render_value(v) {
107            // `render_value` tags every bare enum `IFCBOOLEAN`, which is right
108            // for a property's NominalValue (there the tokens are the T/F/U
109            // logicals) and wrong here, where `.NOTDEFINED.` and `.PLAIN.` are
110            // ordinary enumerations. Tagging those boolean invites a consumer
111            // to parse them as one.
112            if matches!(v, AttributeValue::Enum(e) if !matches!(e.as_str(), "T" | "F" | "U")) {
113                value_type = "IFCENUM".to_string();
114            }
115            out.push(PropValue {
116                name: (*name).to_string(),
117                value,
118                value_type,
119                kind,
120            });
121        }
122    }
123    out
124}
125
126pub fn opt_string(av: Option<&AttributeValue>) -> Option<String> {
127    av.and_then(|a| a.as_string()).map(|s| s.to_string()).filter(|s| !s.is_empty())
128}
129
130/// Collect the entity references in a STEP list attribute (e.g. `(#44,#45)`),
131/// dropping nulls/non-refs. An absent or `$` attribute yields an empty `Vec`.
132pub fn ref_list(av: Option<&AttributeValue>) -> Vec<u32> {
133    av.and_then(|a| a.as_list())
134        .map(|items| items.iter().filter_map(|v| v.as_entity_ref()).collect())
135        .unwrap_or_default()
136}
137
138/// The property kinds the flat exports write: all seven (EXPORT-DATA-2, D47).
139///
140/// CSV, JSON, JSON-LD, IFCX, USD, BOS and the Python `entity_data` carry an
141/// `IfcPropertySingleValue` as its raw nominal value, and every other kind
142/// (enumerated, list, bounded, table, reference, complex) as the columnar
143/// display string the server and the viewer show, typed `kind = Text` with
144/// `value_type` = the members' shared type tag, else the property class
145/// keyword ([`flat_property`]). Complex properties are walked under the
146/// model's one complex-property budget (#7675), charged in the order the
147/// stream decodes the sets.
148pub const EXPORT_PROPERTY_SCOPE: PropertyScope = PropertyScope::Flat;
149
150/// The model's property decoder: one per export, so one complex-property
151/// budget per model (#7675).
152pub fn new_property_decoder(input_len: usize) -> PropertyDecoder {
153    PropertyDecoder::for_input(input_len, EXPORT_PROPERTY_SCOPE)
154}
155
156/// One decoded property in the flat exports' shape; `None` for a nameless
157/// property or one with no value to show.
158pub fn flat_property(row: &PropertyRow) -> Option<PropValue> {
159    if row.name.is_empty() {
160        return None;
161    }
162    if let Some(nominal) = &row.nominal {
163        let Rendered { value, value_type, kind } = render_value(nominal)?;
164        return Some(PropValue { name: row.name.clone(), value, value_type, kind });
165    }
166    if row.kind == PropertyKind::Single {
167        return None;
168    }
169    // D47: the columnar display string as text, typed by the members' shared
170    // tag when they have one, else by the property class.
171    let display = row.display.as_ref().filter(|d| d.property_type != "null")?;
172    Some(PropValue {
173        name: row.name.clone(),
174        value: display.property_value.clone(),
175        value_type: display.data_type.clone().unwrap_or_else(|| row.kind.class_keyword().to_string()),
176        kind: ValueKind::Text,
177    })
178}
179
180#[cfg(test)]
181#[path = "flat_tests.rs"]
182mod props_tests;
183
184/// Decode one `IfcPropertySet` definition into our model.
185pub fn decode_property_set(
186    props: &mut PropertyDecoder, decoder: &mut EntityDecoder, def: &DecodedEntity,
187) -> Option<PropertySet> {
188    decode_property_set_with_kinds(props, decoder, def, None)
189}
190
191fn decode_property_set_with_kinds(
192    props: &mut PropertyDecoder, decoder: &mut EntityDecoder, def: &DecodedEntity,
193    mut kinds: Option<&mut Vec<PropertyKind>>,
194) -> Option<PropertySet> {
195    let row = props.decode_set(decoder, def)?;
196    let properties = row.properties.iter().filter_map(|row| {
197        let value = flat_property(row)?;
198        if let Some(kinds) = kinds.as_deref_mut() { kinds.push(row.kind); }
199        Some(value)
200    }).collect();
201    Some(PropertySet { name: row.name.unwrap_or_default(), properties })
202}
203
204/// Resolve a list of property/quantity set definition ids into non-empty
205/// `(property_sets, quantity_sets)`, dropping undecodable refs. Each id is
206/// resolved on its own, so a repeated id yields a repeated set.
207#[deprecated(
208    since = "21.5.0",
209    note = "use `data_model::rows::stream_export_model`, whose rows carry resolved property and quantity sets"
210)]
211pub fn resolve_pset_defs(
212    props: &mut PropertyDecoder,
213    decoder: &mut EntityDecoder,
214    def_ids: &[u32],
215) -> (Vec<PropertySet>, Vec<QuantitySet>) {
216    resolve_pset_defs_with_kinds(props, decoder, def_ids, None)
217}
218
219/// Resolve a list of property/quantity set definition ids into non-empty
220/// `(property_sets, quantity_sets)`, dropping undecodable refs. Each id is
221/// resolved on its own, so a repeated id yields a repeated set. When `kinds`
222/// is given, pushes one entry per kept property set, index-aligned with the
223/// returned `property_sets`.
224pub(crate) fn resolve_pset_defs_with_kinds(
225    props: &mut PropertyDecoder,
226    decoder: &mut EntityDecoder,
227    def_ids: &[u32],
228    mut kinds: Option<&mut Vec<Vec<PropertyKind>>>,
229) -> (Vec<PropertySet>, Vec<QuantitySet>) {
230    let mut property_sets = Vec::new();
231    let mut quantity_sets = Vec::new();
232    for &def_id in def_ids {
233        let mut set_kinds = Vec::new();
234        let capture = kinds.is_some().then_some(&mut set_kinds);
235        match resolve_def(props, decoder, def_id, capture) {
236            Some((_, Resolved::Properties(ps))) => {
237                if let Some(kinds) = kinds.as_deref_mut() { kinds.push(set_kinds); }
238                property_sets.push(ps);
239            }
240            Some((_, Resolved::Quantities(qs))) => quantity_sets.push(qs),
241            None => {}
242        }
243    }
244    (property_sets, quantity_sets)
245}
246
247/// A resolved, non-empty set definition, and whether it is a quantity set.
248enum Resolved {
249    Properties(PropertySet),
250    Quantities(QuantitySet),
251}
252
253/// One definition, resolved, with the entity it was read from. `None` for an
254/// undecodable ref, anything that is not a property or quantity set, and a set
255/// with no entry this export decodes. `kinds` captures each kept property's
256/// kind, as in [`decode_property_set_with_kinds`].
257fn resolve_def(
258    props: &mut PropertyDecoder,
259    decoder: &mut EntityDecoder,
260    def_id: u32,
261    kinds: Option<&mut Vec<PropertyKind>>,
262) -> Option<(DecodedEntity, Resolved)> {
263    let def = decoder.decode_by_id(def_id).ok()?;
264    let set = match def.ifc_type {
265        IfcType::IfcPropertySet => decode_property_set_with_kinds(props, decoder, &def, kinds)
266            .filter(|ps| !ps.properties.is_empty())
267            .map(Resolved::Properties),
268        IfcType::IfcElementQuantity => {
269            decode_quantity_set(decoder, &def).filter(|qs| !qs.quantities.is_empty()).map(Resolved::Quantities)
270        }
271        _ => None,
272    }?;
273    Some((def, set))
274}
275
276/// The sets a type carries, read the way the TS type extractor reads them:
277/// its own `HasPropertySets` first, then the definitions
278/// `IfcRelDefinesByProperties` attaches to it. Each definition id is read once
279/// across both. A relationship-attached set is also skipped when a set already
280/// taken has the same Name and GlobalId, so one set written twice under two
281/// ids is not inherited twice. Only non-empty sets take part, so an empty set
282/// never hides a populated one.
283pub(crate) fn resolve_type_sets(
284    props: &mut PropertyDecoder,
285    decoder: &mut EntityDecoder,
286    has_property_sets: Vec<u32>,
287    related: &[u32],
288) -> (Vec<PropertySet>, Vec<QuantitySet>) {
289    let mut seen_ids = HashSet::new();
290    let (mut psets, mut qsets) = (Vec::new(), Vec::new());
291    let mut seen_keys = HashSet::new();
292    // HasPropertySets entries are always taken and only record their key;
293    // relationship-attached ones are skipped when the key is already taken.
294    let first = has_property_sets.into_iter().map(|id| (id, false));
295    let fresh = related.iter().map(|&id| (id, true));
296    for (id, skippable) in first.chain(fresh) {
297        if !seen_ids.insert(id) { continue; }
298        let Some((def, set)) = resolve_def(props, decoder, id, None) else { continue };
299        let gid = def.string_at(slot::IfcRoot::GLOBAL_ID).unwrap_or("");
300        let (is_qset, name) = match &set {
301            Resolved::Properties(ps) => (false, &ps.name),
302            Resolved::Quantities(qs) => (true, &qs.name),
303        };
304        // Property and quantity sets are keyed apart, as the TS extractor
305        // resolves them as separate lists. A set with neither a Name nor a
306        // GlobalId has no identity beyond its id.
307        let has_identity = !name.is_empty() || !gid.is_empty();
308        if has_identity && !seen_keys.insert((is_qset, name.clone(), gid.to_owned())) && skippable {
309            continue;
310        }
311        match set {
312            Resolved::Properties(ps) => psets.push(ps),
313            Resolved::Quantities(qs) => qsets.push(qs),
314        }
315    }
316    (psets, qsets)
317}
318
319#[cfg(test)]
320mod tests {
321    use super::*;
322
323    fn s(text: &str) -> AttributeValue {
324        AttributeValue::String(text.to_owned())
325    }
326
327    /// CORE-4 (#7776): `IfcPerson.MiddleNames ('Anne','Marie')` is a list of
328    /// two strings. It rendered as the value `Marie` tagged `Anne`.
329    #[test]
330    fn a_two_string_list_is_not_a_typed_value_core_4_7776() {
331        assert!(render_value(&AttributeValue::List(vec![s("Anne"), s("Marie")])).is_none());
332        let typed = AttributeValue::Typed { name: "IFCLABEL".into(), value: Box::new(s("Marie")) };
333        let rendered = render_value(&typed).expect("a typed value renders");
334        assert_eq!((rendered.value.as_str(), rendered.value_type.as_str()), ("Marie", "IFCLABEL"));
335    }
336}