Skip to main content

ifc_template_catalog/
export.rs

1//! Deterministic, diffable IFC template applicability export.
2
3use std::io::{self, Write};
4
5use crate::catalog::Catalog;
6use crate::definition::{
7    Applicability, CatalogEdition, PropertyDataType, PropertyKind, PropertySetType,
8    PropertyTemplate, QuantityKind, QuantitySetType, SetTemplate, SetTemplateKind,
9};
10
11/// TSV column header row emitted by [`write_applicability_tsv`], including trailing newline.
12pub const TSV_HEADER: &str = "edition\tsource_digest\tset_kind\tset_name\tset_guid\tset_template_type\tapplicable_entity\tpredefined_type\tincludes_subtypes\tmember_path\tmember_guid\tmember_kind\tvalue_type\tunit_type\tsource_path\tsource_file_digest\n";
13
14/// Counts summarizing one [`write_applicability_tsv`] export.
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16#[non_exhaustive]
17pub struct ExportSummary {
18    /// Total set templates (property + quantity) exported.
19    pub set_count: usize,
20    /// Property-set templates exported.
21    pub property_set_count: usize,
22    /// Quantity-set templates exported.
23    pub quantity_set_count: usize,
24    /// Total data rows written, after applicability expansion and sorting.
25    pub row_count: usize,
26}
27
28/// Write every catalog template as sorted, tab-separated applicability rows,
29/// one row per (set, applicability selector, member) combination, preceded
30/// by [`TSV_HEADER`]. Sets with no applicability selectors emit one row per
31/// member with empty entity/predefined-type columns.
32pub fn write_applicability_tsv(
33    catalog: &Catalog,
34    mut output: impl Write,
35) -> io::Result<ExportSummary> {
36    let manifest = catalog.manifest();
37    let mut rows = Vec::new();
38    let mut property_set_count = 0;
39    let mut quantity_set_count = 0;
40    for set in catalog.iter() {
41        match &set.kind {
42            SetTemplateKind::Property { .. } => property_set_count += 1,
43            SetTemplateKind::Quantity { .. } => quantity_set_count += 1,
44        }
45        if set.applicability.is_empty() {
46            append_set_rows(&mut rows, set, None, manifest.edition, &manifest.sha256);
47        } else {
48            for applicability in &set.applicability {
49                append_set_rows(
50                    &mut rows,
51                    set,
52                    Some(applicability),
53                    manifest.edition,
54                    &manifest.sha256,
55                );
56            }
57        }
58    }
59    rows.sort_unstable();
60    writeln!(output, "{TSV_HEADER}")?;
61    for row in &rows {
62        writeln!(output, "{row}")?;
63    }
64    Ok(ExportSummary {
65        set_count: catalog.len(),
66        property_set_count,
67        quantity_set_count,
68        row_count: rows.len(),
69    })
70}
71
72fn append_set_rows(
73    rows: &mut Vec<String>,
74    set: &SetTemplate,
75    applicability: Option<&Applicability>,
76    edition: CatalogEdition,
77    source_digest: &str,
78) {
79    match &set.kind {
80        SetTemplateKind::Property {
81            set_type,
82            properties,
83        } => {
84            for property in properties {
85                append_property_rows(
86                    rows,
87                    set,
88                    applicability,
89                    edition,
90                    source_digest,
91                    property_set_type(*set_type),
92                    "",
93                    property,
94                );
95            }
96        }
97        SetTemplateKind::Quantity {
98            set_type,
99            quantities,
100            ..
101        } => {
102            for quantity in quantities {
103                append_row(
104                    rows,
105                    set,
106                    applicability,
107                    edition,
108                    source_digest,
109                    "qto",
110                    quantity_set_type(*set_type),
111                    &quantity.name,
112                    "",
113                    quantity_kind(quantity.kind),
114                    quantity_value_type(quantity.kind),
115                    "",
116                );
117            }
118        }
119    }
120}
121
122#[allow(clippy::too_many_arguments)]
123fn append_property_rows(
124    rows: &mut Vec<String>,
125    set: &SetTemplate,
126    applicability: Option<&Applicability>,
127    edition: CatalogEdition,
128    source_digest: &str,
129    set_type: &str,
130    parent_path: &str,
131    property: &PropertyTemplate,
132) {
133    let path = if parent_path.is_empty() {
134        property.name.clone()
135    } else {
136        format!("{parent_path}.{}", property.name)
137    };
138    let (kind, value_type, unit_type) = property_kind(&property.kind);
139    append_row(
140        rows,
141        set,
142        applicability,
143        edition,
144        source_digest,
145        "psd",
146        set_type,
147        &path,
148        property.guid.as_deref().unwrap_or(""),
149        kind,
150        &value_type,
151        &unit_type,
152    );
153    if let PropertyKind::Complex { properties, .. } = &property.kind {
154        for nested in properties {
155            append_property_rows(
156                rows,
157                set,
158                applicability,
159                edition,
160                source_digest,
161                set_type,
162                &path,
163                nested,
164            );
165        }
166    }
167}
168
169#[allow(clippy::too_many_arguments)]
170fn append_row(
171    rows: &mut Vec<String>,
172    set: &SetTemplate,
173    applicability: Option<&Applicability>,
174    edition: CatalogEdition,
175    source_digest: &str,
176    set_kind: &str,
177    set_type: &str,
178    member_path: &str,
179    member_guid: &str,
180    member_kind: &str,
181    value_type: &str,
182    unit_type: &str,
183) {
184    let source = set.source.as_ref();
185    let fields = [
186        edition_name(edition),
187        source_digest,
188        set_kind,
189        &set.name,
190        set.guid.as_deref().unwrap_or(""),
191        set_type,
192        applicability.map_or("", |value| value.entity.as_str()),
193        applicability
194            .and_then(|value| value.predefined_type.as_deref())
195            .unwrap_or(""),
196        "true",
197        member_path,
198        member_guid,
199        member_kind,
200        value_type,
201        unit_type,
202        source.map_or("", |value| value.relative_path.as_str()),
203        source.map_or("", |value| value.sha256.as_str()),
204    ];
205    rows.push(fields.map(escape).join("\t"));
206}
207
208fn property_kind(kind: &PropertyKind) -> (&'static str, String, String) {
209    match kind {
210        PropertyKind::SingleValue { data_type } => property_type("single", data_type),
211        PropertyKind::BoundedValue { data_type } => property_type("bounded", data_type),
212        PropertyKind::EnumeratedValue {
213            enumeration_name,
214            data_type,
215            ..
216        } => (
217            "enumerated",
218            data_type
219                .as_ref()
220                .and_then(|value| value.type_name.clone())
221                .or_else(|| enumeration_name.clone())
222                .unwrap_or_default(),
223            data_type
224                .as_ref()
225                .and_then(|value| value.unit_type.clone())
226                .unwrap_or_default(),
227        ),
228        PropertyKind::ListValue { data_type } => property_type("list", data_type),
229        PropertyKind::ReferenceValue { reference_type } => {
230            ("reference", reference_type.clone(), String::new())
231        }
232        PropertyKind::TableValue {
233            defining_type,
234            defined_type,
235            ..
236        } => (
237            "table",
238            format!(
239                "{}->{}",
240                defining_type.type_name.as_deref().unwrap_or(""),
241                defined_type.type_name.as_deref().unwrap_or("")
242            ),
243            String::new(),
244        ),
245        PropertyKind::Complex { usage_name, .. } => ("complex", usage_name.clone(), String::new()),
246    }
247}
248
249fn property_type(
250    kind: &'static str,
251    data_type: &PropertyDataType,
252) -> (&'static str, String, String) {
253    (
254        kind,
255        data_type.type_name.clone().unwrap_or_default(),
256        data_type.unit_type.clone().unwrap_or_default(),
257    )
258}
259
260fn escape(value: &str) -> String {
261    value
262        .replace('\\', "\\\\")
263        .replace('\t', "\\t")
264        .replace('\r', "\\r")
265        .replace('\n', "\\n")
266}
267
268fn edition_name(value: CatalogEdition) -> &'static str {
269    match value {
270        CatalogEdition::Ifc2x3Tc1 => "IFC2X3_TC1",
271        CatalogEdition::Ifc4Add2Tc1 => "IFC4_ADD2_TC1",
272        CatalogEdition::Ifc4x3Add2 => "IFC4X3_ADD2",
273    }
274}
275
276fn property_set_type(value: PropertySetType) -> &'static str {
277    match value {
278        PropertySetType::TypeDrivenOverride => "type-driven-override",
279        PropertySetType::TypeDrivenOnly => "type-driven-only",
280        PropertySetType::OccurrenceDriven => "occurrence-driven",
281        PropertySetType::PerformanceDriven => "performance-driven",
282        PropertySetType::Unspecified => "unspecified",
283    }
284}
285
286fn quantity_set_type(value: QuantitySetType) -> &'static str {
287    match value {
288        QuantitySetType::TypeDrivenOverride => "type-driven-override",
289        QuantitySetType::TypeDrivenOnly => "type-driven-only",
290        QuantitySetType::OccurrenceDriven => "occurrence-driven",
291        QuantitySetType::Unspecified => "unspecified",
292    }
293}
294
295fn quantity_kind(value: QuantityKind) -> &'static str {
296    match value {
297        QuantityKind::Length => "length",
298        QuantityKind::Area => "area",
299        QuantityKind::Volume => "volume",
300        QuantityKind::Weight => "weight",
301        QuantityKind::Time => "time",
302        QuantityKind::Count => "count",
303        QuantityKind::Number => "number",
304    }
305}
306
307fn quantity_value_type(value: QuantityKind) -> &'static str {
308    match value {
309        QuantityKind::Length => "Q_LENGTH",
310        QuantityKind::Area => "Q_AREA",
311        QuantityKind::Volume => "Q_VOLUME",
312        QuantityKind::Weight => "Q_WEIGHT",
313        QuantityKind::Time => "Q_TIME",
314        QuantityKind::Count => "Q_COUNT",
315        QuantityKind::Number => "Q_NUMBER",
316    }
317}