openbim-step 0.6.2

Generic ISO 10303 STEP Part 21 and EXPRESS syntax infrastructure
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
#![allow(missing_docs)]

use openbim_step::express::{parse, Attribute, EntityDef, ParsedSchema, TypeDef, TypeKind};

#[test]
fn schema_model_builders_preserve_the_ifc_schema_surface() {
    let attribute = Attribute::new("Items", "IfcLabel").optional().aggregate();
    assert!(attribute.optional);
    assert!(attribute.aggregate);

    let entity = EntityDef::new("IfcExample")
        .with_supertype("IfcRoot")
        .with_attribute(attribute);
    assert_eq!(entity.supertype(), Some("IfcRoot"));
    assert_eq!(entity.attributes.len(), 1);

    let defined = TypeDef {
        name: "IfcLabel".into(),
        kind: TypeKind::Defined("STRING".into()),
    };
    assert!(defined.is_defined());
}

const SCHEMA: &str = r"
SCHEMA DEMO;
(* ENTITY Fake; value : TEXT; END_ENTITY; *)
TYPE Distance = REAL;
END_TYPE;
TYPE Shade = ENUMERATION OF (RED, GREEN, BLUE);
END_TYPE;
TYPE AnyValue = SELECT (Distance, Shade);
END_TYPE;
ENTITY Root ABSTRACT SUPERTYPE OF (ONEOF(Item));
  Label : OPTIONAL STRING;
END_ENTITY;
ENTITY Item SUBTYPE OF (Root);
  Size : Distance;
  Points : LIST [1:?] OF Distance;
DERIVE
  Doubled : Distance := Size * 2;
WHERE
  Positive : Size > 0;
END_ENTITY;
END_SCHEMA;
";

#[test]
fn structural_partial_express_parser_extracts_supported_declarations() {
    let ParsedSchema {
        name,
        entities,
        types,
    } = parse(SCHEMA);
    assert_eq!(name, "DEMO");
    assert_eq!(entities.len(), 2);
    assert_eq!(types.len(), 3);

    let root = &entities[0];
    assert_eq!(
        root,
        &EntityDef {
            name: "Root".into(),
            supertypes: Vec::new(),
            abstract_: true,
            attributes: vec![Attribute {
                name: "Label".into(),
                type_name: "STRING".into(),
                optional: true,
                aggregate: false
            }],
            derived: Vec::new(),
            redeclared: Vec::new(),
            where_rules: Vec::new(),
        }
    );
    let item = &entities[1];
    assert_eq!(item.supertype(), Some("Root"));
    assert_eq!(
        item.attributes.len(),
        2,
        "DERIVE and WHERE are not explicit slots"
    );
    assert!(item.attributes[1].aggregate);

    assert_eq!(
        types[0],
        TypeDef {
            name: "Distance".into(),
            kind: TypeKind::Defined("REAL".into())
        }
    );
    assert_eq!(
        types[1].kind,
        TypeKind::Enumeration(vec!["RED".into(), "GREEN".into(), "BLUE".into()])
    );
    assert_eq!(
        types[2].kind,
        TypeKind::Select(vec!["Distance".into(), "Shade".into()])
    );
}

/// A subtype may redeclare an inherited attribute as DERIVED. Part 21 writes
/// such a slot as `*`, which is neither a value nor `$`, so a writer that does
/// not know the attribute is derived cannot produce a conforming file.
#[test]
fn derive_blocks_report_redeclared_attribute_names() {
    let source = "\
SCHEMA test;
ENTITY parent;
  Precision : REAL;
  Dimension : INTEGER;
END_ENTITY;
ENTITY child
 SUBTYPE OF (parent);
  ParentRef : parent;
 DERIVE
  SELF\\parent.Precision : REAL := NVL(ParentRef.Precision, 1.E-5);
  SELF\\parent.Dimension : INTEGER := ParentRef.Dimension;
 WHERE
  NoSub : TRUE;
END_ENTITY;
END_SCHEMA;
";
    let schema = parse(source);
    let child = schema
        .entities
        .iter()
        .find(|entity| entity.name == "child")
        .expect("child entity");

    assert_eq!(
        child.derived,
        vec!["Precision".to_owned(), "Dimension".to_owned()],
        "the SELF\\Entity. prefix names the supertype, not the attribute"
    );
    assert!(
        child.is_derived("precision"),
        "matching is case-insensitive"
    );
    assert!(
        !child.is_derived("ParentRef"),
        "explicit attributes are not derived"
    );

    // The WHERE clause must not leak into the derived list.
    assert!(!child.is_derived("NoSub"));

    // An entity without a DERIVE block reports none.
    let parent = schema
        .entities
        .iter()
        .find(|entity| entity.name == "parent")
        .expect("parent entity");
    assert!(parent.derived.is_empty());
}

/// A derived attribute that is not a redeclaration has no qualifying prefix.
#[test]
fn unqualified_derived_attributes_are_reported() {
    let source = "\
SCHEMA test;
ENTITY thing;
  Length : REAL;
 DERIVE
  Area : REAL := Length * Length;
END_ENTITY;
END_SCHEMA;
";
    let schema = parse(source);
    let thing = &schema.entities[0];
    assert_eq!(thing.derived, vec!["Area".to_owned()]);
    assert_eq!(
        thing.attributes.len(),
        1,
        "a derived attribute is not an explicit positional attribute"
    );
}

/// The DERIVE block must end where the next clause begins.
///
/// A single WHERE rule cannot prove this: its statement still carries the
/// `WHERE` keyword, so it fails the identifier check by accident. From the
/// second rule onward the keyword is gone and a bad boundary silently reports
/// rule labels as derived attributes. Real schemas routinely have several.
#[test]
fn where_rule_labels_are_not_reported_as_derived() {
    let source = "\
SCHEMA test;
ENTITY child;
  ParentRef : INTEGER;
 DERIVE
  SELF\\parent.Precision : REAL := 1.0;
 WHERE
  FirstRule : TRUE;
  SecondRule : TRUE;
  ThirdRule : TRUE;
END_ENTITY;
END_SCHEMA;
";
    let schema = parse(source);
    let child = &schema.entities[0];
    assert_eq!(
        child.derived,
        vec!["Precision".to_owned()],
        "only the DERIVE statement, not the WHERE rule labels"
    );
    for rule in ["FirstRule", "SecondRule", "ThirdRule"] {
        assert!(
            !child.is_derived(rule),
            "{rule} is a constraint, not an attribute"
        );
    }
}

/// The same boundary, for the other clauses that can follow DERIVE.
#[test]
fn inverse_and_unique_clauses_do_not_leak_into_derived() {
    let source = "\
SCHEMA test;
ENTITY child;
  Ref : INTEGER;
 DERIVE
  Computed : REAL := 1.0;
 INVERSE
  FirstBack : SET OF other FOR Ref;
  SecondBack : SET OF other FOR Ref;
 UNIQUE
  FirstKey : Ref;
  SecondKey : Ref;
END_ENTITY;
END_SCHEMA;
";
    let schema = parse(source);
    let child = &schema.entities[0];
    assert_eq!(child.derived, vec!["Computed".to_owned()]);
    for name in ["FirstBack", "SecondBack", "FirstKey", "SecondKey"] {
        assert!(!child.is_derived(name), "{name} must not be derived");
    }
}

/// `UNIQUE` inside an aggregate declaration does not end the attribute list.
///
/// EXPRESS reuses block keywords as declaration modifiers: `LIST [1:?] OF
/// UNIQUE X` is an attribute, not a UNIQUE block. Ending the body at the first
/// occurrence truncated the entity, and every attribute after it vanished.
/// `IfcTypeProduct` lost `RepresentationMaps` and `Tag` this way, which made
/// every IFC product type impossible to author.
#[test]
fn a_unique_aggregate_does_not_truncate_the_attribute_list() {
    let source = "\
ENTITY Holder
 SUPERTYPE OF (ONEOF
    (SubA
    ,SubB))
 SUBTYPE OF (Base);
\tMaps : OPTIONAL LIST [1:?] OF UNIQUE Target;
\tTag : OPTIONAL Label;
 INVERSE
\tUsedBy : SET [0:?] OF Other FOR Thing;
 WHERE
\tRule : EXISTS(Tag);
END_ENTITY;
";
    let schema = parse(source);
    let holder = schema
        .entities
        .iter()
        .find(|entity| entity.name == "Holder")
        .expect("Holder parsed");

    let names: Vec<&str> = holder
        .attributes
        .iter()
        .map(|attribute| attribute.name.as_str())
        .collect();
    assert_eq!(
        names,
        ["Maps", "Tag"],
        "the attribute after the inline UNIQUE must survive"
    );
    assert_eq!(holder.supertype(), Some("Base"));
}

/// A real `UNIQUE` block still ends the attribute list.
///
/// The fix must not swing the other way and swallow genuine blocks.
#[test]
fn a_statement_level_unique_block_still_ends_the_attributes() {
    let source = "\
ENTITY Thing;
\tName : Label;
 UNIQUE
\tOnlyOne : Name;
END_ENTITY;
";
    let schema = parse(source);
    let thing = schema
        .entities
        .iter()
        .find(|entity| entity.name == "Thing")
        .expect("Thing parsed");
    let names: Vec<&str> = thing
        .attributes
        .iter()
        .map(|attribute| attribute.name.as_str())
        .collect();
    assert_eq!(names, ["Name"], "the UNIQUE block is not an attribute");
}

/// A `WHERE` block is captured as labelled rules.
///
/// Recording that a constraint exists, and what it says, is what lets a
/// consumer prove "no rule constrains this" instead of asserting it from
/// prose. The expression is kept verbatim; evaluating EXPRESS is a separate
/// concern.
#[test]
fn where_rules_are_captured_with_labels_and_expressions() {
    let source = "\
ENTITY IfcSurfaceCurve
 SUBTYPE OF (IfcCurve);
\tCurve3D : IfcCurve;
 WHERE
\tCurveIs3D : Curve3D.Dim = 3;
\tCurveIsNotPcurve : NOT ('IFC4.IFCPCURVE' IN TYPEOF(Curve3D));
END_ENTITY;";
    let schema = parse(source);
    let entity = schema
        .entities
        .iter()
        .find(|entity| entity.name.eq_ignore_ascii_case("IfcSurfaceCurve"))
        .expect("entity");
    let labels: Vec<_> = entity
        .where_rules
        .iter()
        .map(|r| r.label.as_str())
        .collect();
    assert_eq!(labels, ["CurveIs3D", "CurveIsNotPcurve"]);
    assert_eq!(entity.where_rules[0].expression, "Curve3D.Dim = 3");
    assert_eq!(
        entity.where_rules[1].expression,
        "NOT ('IFC4.IFCPCURVE' IN TYPEOF(Curve3D))"
    );
    // The attribute list must survive the WHERE block.
    assert_eq!(entity.attributes.len(), 1);
}

/// A multi-line rule body is captured whole, not cut at the first newline.
///
/// Rule expressions routinely span lines and nest `QUERY(x <* set | predicate)`;
/// `IfcAdvancedFace` in IFC4X3 declares three such rules, the longest running
/// eleven lines. Whitespace is normalised so the stored text stays comparable.
///
/// The block start uses `find_block_keyword` for the same reason the attribute
/// list does -- a statement-level check rather than a keyword search. No IFC4X3
/// entity currently writes `WHERE` inside an earlier block, so that choice is
/// defence against a legal schema this parser has not met, not a fix for an
/// observed break.
#[test]
fn a_multi_line_query_rule_is_captured_whole() {
    let source = "\
ENTITY Face;
\tBounds : SET OF Bound;
 WHERE
\tFirstRule : SIZEOF(QUERY (b <* Bounds |
\t  NOT ('SCHEMA.LOOP' IN TYPEOF(b)))) = 0;
\tSecondRule : SIZEOF(Bounds) > 0;
END_ENTITY;";
    let schema = parse(source);
    let entity = schema
        .entities
        .iter()
        .find(|entity| entity.name.eq_ignore_ascii_case("Face"))
        .expect("entity");
    let labels: Vec<_> = entity
        .where_rules
        .iter()
        .map(|r| r.label.as_str())
        .collect();
    assert_eq!(labels, ["FirstRule", "SecondRule"]);
    // The multi-line rule is normalised to one line, not cut at the newline.
    assert_eq!(
        entity.where_rules[0].expression,
        "SIZEOF(QUERY (b <* Bounds | NOT ('SCHEMA.LOOP' IN TYPEOF(b)))) = 0"
    );
    assert_eq!(entity.attributes.len(), 1);
}

/// `WHERE` appearing inside an earlier block does not start the rule block.
///
/// No IFC4X3 entity does this, but EXPRESS permits it and a keyword search
/// would take the DERIVE-block occurrence as the block start, silently
/// dropping every real rule. This pins the statement-level behaviour.
#[test]
fn a_where_token_inside_an_earlier_block_is_not_the_block_start() {
    let source = "\
ENTITY Holder;
\tItems : SET OF Item;
 DERIVE
\tPicked : Item := QUERY(i <* SELF.Items | i.Kind = 'WHERE')[1];
 WHERE
\tRealRule : SIZEOF(Items) > 0;
END_ENTITY;";
    let schema = parse(source);
    let entity = schema
        .entities
        .iter()
        .find(|entity| entity.name.eq_ignore_ascii_case("Holder"))
        .expect("entity");
    let labels: Vec<_> = entity
        .where_rules
        .iter()
        .map(|r| r.label.as_str())
        .collect();
    assert_eq!(labels, ["RealRule"]);
    assert_eq!(entity.derived, ["Picked"]);
}

// ---- #2 multiple inheritance, #3 explicit redeclarations -----------------
// ISO 10303-21:2016 §12.2.5.2: supertypes are processed in SUBTYPE OF order,
// higher supertypes first, and a supertype reached twice counts once.
// §12.2.8: an explicit `SELF\X.a` redeclaration keeps X's slot and adds none.

const MULTI: &str = r"
SCHEMA M;
ENTITY top; t : INTEGER; END_ENTITY;
ENTITY a SUBTYPE OF (top); x : INTEGER; END_ENTITY;
ENTITY b SUBTYPE OF (top); y : INTEGER; END_ENTITY;
ENTITY c SUBTYPE OF (a, b); z : INTEGER; END_ENTITY;
END_SCHEMA;
";

#[test]
fn every_declared_supertype_is_recorded_in_order() {
    let parsed = parse(MULTI);
    let c = parsed.entities.iter().find(|e| e.name == "c").unwrap();
    assert_eq!(c.supertypes, ["a", "b"]);
    assert_eq!(c.supertype(), Some("a"));
    let top = parsed.entities.iter().find(|e| e.name == "top").unwrap();
    assert!(top.supertypes.is_empty());
    assert_eq!(top.supertype(), None);
}

const REDECLARED: &str = r"
SCHEMA R;
ENTITY styled; name : STRING; target : thing; END_ENTITY;
ENTITY plane SUBTYPE OF (styled);
  SELF\styled.target : plane_target;
  extra : INTEGER;
END_ENTITY;
END_SCHEMA;
";

#[test]
fn explicit_redeclarations_are_not_new_attributes() {
    let parsed = parse(REDECLARED);
    let plane = parsed.entities.iter().find(|e| e.name == "plane").unwrap();
    let names: Vec<_> = plane.attributes.iter().map(|a| a.name.as_str()).collect();
    assert_eq!(names, ["extra"]);
    assert_eq!(plane.redeclared.len(), 1);
    let r = &plane.redeclared[0];
    assert_eq!(
        (r.supertype.as_str(), r.name.as_str(), r.type_name.as_str()),
        ("styled", "target", "plane_target")
    );
    assert!(plane.is_redeclared("TARGET"));
    assert!(!plane.is_redeclared("extra"));
}