cadmpeg-ir 0.6.2

CAD data model, validation, diffing, and codec API for cadmpeg.
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
468
469
470
471
472
473
474
475
476
477
// SPDX-License-Identifier: Apache-2.0
//! Validation of borrowed annotations and native product links.

use crate::document::CadIr;
use crate::index::identities::{BorrowedIdentities, IdentitySet};
use crate::native::view::{NativeEntity, NativeView};
use crate::report::{
    check::{Check, Finding},
    Severity,
};
use cadmpeg_core::decode::DecodeContext;
use cadmpeg_core::CodecError;
use serde_value::Value;

enum AnnotatedEntity<'ir> {
    Projected(crate::schema::structural::Projection),
    Product(&'ir crate::native::NativeRecord),
    Source(&'ir crate::unknown::UnknownRecord),
}

macro_rules! define_model_entity_projection {
    ($( $field:ident: $element:ty, $doc:literal, [$($attribute:meta),*] $(, [$($schema_attr:meta),*])?; )*) => {
        fn model_entity_projection<'ir>(
            ctx: &DecodeContext<'_>,
            ir: &'ir CadIr,
            wanted: &BorrowedIdentities<'_, bool>,
            add: &mut dyn FnMut(&'ir str, AnnotatedEntity<'ir>),
        ) -> Result<(), CodecError> {
            $(for entity in &ir.model.$field {
                let id = crate::schema::EntitySchema::identity(entity);
                if wanted.contains(id) {
                    let value = match crate::schema::structural::project(ctx, entity, "annotated entity projection") {
                        Ok(value) => value,
                        Err(error @ CodecError::ResourceLimit(_)) => return Err(error),
                        Err(_) => continue,
                    };
                    add(id, AnnotatedEntity::Projected(value));
                }
            })*
            Ok(())
        }
    };
}
crate::document::arena_registry!(define_model_entity_projection);

pub(super) fn check_annotations(
    ctx: &DecodeContext<'_>,
    view: NativeView<'_>,
    annotations: &crate::Annotations,
    all_ids: &dyn IdentitySet,
    findings: &mut Vec<Finding>,
) -> Result<(), CodecError> {
    let mut wanted = BorrowedIdentities::build(|add| {
        for (id, note) in annotations.exactness() {
            if !note.fields().is_empty() {
                add(id, false);
            }
        }
    });
    let mut values = Vec::new();
    let mut entities = BorrowedIdentities::new();
    // Sort small identity slots rather than moving projected payloads.
    let mut add = |id, value| {
        entities.insert(id, values.len());
        values.push(value);
    };
    view.for_each(|_, _, records| {
        for record in records.records() {
            let Some(seen) = wanted.get_mut(record.id()) else {
                continue;
            };
            if *seen {
                continue;
            }
            *seen = true;
            let value = match record {
                NativeEntity::Product(product) => AnnotatedEntity::Product(product),
                NativeEntity::Source(source) => AnnotatedEntity::Source(source),
            };
            add(record.id(), value);
        }
    });
    // Model entities take precedence over native records with the same id.
    // The identity index keeps the last inserted matching value.
    model_entity_projection(ctx, view.ir, &wanted, &mut add)?;
    for id in annotations.provenance.keys() {
        if !all_ids.contains(id) {
            super::record_finding(
                findings,
                Check::Annotations,
                Severity::Error,
                Some(id),
                format_args!("provenance key does not resolve to an entity"),
            );
        }
    }
    for (id, note) in annotations.exactness() {
        if !all_ids.contains(id) {
            super::record_finding(
                findings,
                Check::Annotations,
                Severity::Error,
                Some(id),
                format_args!("exactness key does not resolve to an entity"),
            );
            continue;
        }
        if note.fields().is_empty() {
            continue;
        }
        let Some(position) = entities.get(id) else {
            super::record_finding(
                findings,
                Check::Annotations,
                Severity::Warning,
                Some(id),
                format_args!(
                    "entity could not be serialized to validate its exactness field paths"
                ),
            );
            continue;
        };
        let entity = &values[*position];
        let product_fields = match entity {
            AnnotatedEntity::Product(product) => Some(product.fields()?),
            AnnotatedEntity::Projected(_) | AnnotatedEntity::Source(_) => None,
        };
        for path in note.fields().keys() {
            let resolves = match entity {
                AnnotatedEntity::Projected(value) => field_path_resolves(value, path.as_str()),
                AnnotatedEntity::Product(_) => product_fields
                    .as_ref()
                    .is_some_and(|fields| native_field_path_resolves(fields, path.as_str())),
                AnnotatedEntity::Source(source) => {
                    source_field_path_resolves(source, path.as_str())
                }
            };
            if !resolves {
                super::record_finding(
                    findings,
                    Check::Annotations,
                    Severity::Warning,
                    Some(id),
                    format_args!("exactness field path `{path}` does not resolve"),
                );
            }
        }
    }
    Ok(())
}

/// Whether `path` names a member of a native record, given the record's
/// codec-owned fields.
fn native_field_path_resolves(
    fields: &serde_json::Map<String, serde_json::Value>,
    path: &str,
) -> bool {
    let mut components = path.split('.');
    let Some(first) = components.next() else {
        return false;
    };
    if first == "id" {
        return components.next().is_none();
    }

    let Some(mut value) = fields.get(first) else {
        return false;
    };
    for component in components {
        value = match value {
            serde_json::Value::Object(object) => {
                let mut next = None;
                for (key, child) in object {
                    if key == component {
                        next = Some(child);
                        break;
                    }
                }
                let Some(child) = next else {
                    return false;
                };
                child
            }
            serde_json::Value::Array(array) => {
                let Some(child) = component
                    .parse::<usize>()
                    .ok()
                    .and_then(|index| array.get(index))
                else {
                    return false;
                };
                child
            }
            _ => return false,
        };
    }
    true
}

fn source_field_path_resolves(record: &crate::unknown::UnknownRecord, path: &str) -> bool {
    if path == "id" {
        return true;
    }
    if record.links().is_empty() {
        return false;
    }
    if path == "links" {
        return true;
    }
    path.strip_prefix("links.")
        .and_then(|index| index.parse::<usize>().ok())
        .is_some_and(|index| index < record.links().len())
}

fn field_path_resolves(mut value: &Value, path: &str) -> bool {
    for component in path.split('.') {
        while let Value::Option(Some(inner)) | Value::Newtype(inner) = value {
            value = inner;
        }
        match value {
            Value::Map(object) => {
                let mut next = None;
                for (key, child) in object {
                    if matches!(key, Value::String(key) if key == component) {
                        next = Some(child);
                        break;
                    }
                }
                let Some(child) = next else {
                    return false;
                };
                value = child;
            }
            Value::Seq(array) => {
                let Ok(index) = component.parse::<usize>() else {
                    return false;
                };
                let Some(next) = array.get(index) else {
                    return false;
                };
                value = next;
            }
            _ => return false,
        }
    }
    true
}

pub(super) fn check_native_links(
    view: NativeView<'_>,
    all_ids: &crate::index::ModelIndex<'_>,
    findings: &mut Vec<Finding>,
) {
    let ir = view.ir;
    for feature in &ir.model.features {
        if let Some(target) = &feature.native_ref {
            if !all_ids.native_record_owns(target.as_str()) {
                super::record_finding(
                    findings,
                    Check::NativeLinks,
                    Severity::Error,
                    Some(feature.id.as_str()),
                    format_args!("native_ref `{target}` does not resolve"),
                );
            }
        }
        if let crate::features::FeatureDefinition::Operation(
            crate::features::FeatureOperation::HelixNativeAxis {
                axis_native_ref: target,
                ..
            },
        ) = feature.evaluation.definition()
        {
            if !all_ids.native_record_owns(target.as_str()) {
                super::record_finding(
                    findings,
                    Check::NativeLinks,
                    Severity::Error,
                    Some(feature.id.as_str()),
                    format_args!("helix axis native_ref `{target}` does not resolve"),
                );
            }
        }
    }
    for parameter in &ir.model.parameters {
        if let Some(target) = &parameter.native_ref {
            if !all_ids.native_record_owns(target.as_str()) {
                super::record_finding(
                    findings,
                    Check::NativeLinks,
                    Severity::Error,
                    Some(parameter.id.as_str()),
                    format_args!("native_ref `{target}` does not resolve"),
                );
            }
        }
        if let Some(semantic) = &parameter.pmi {
            if !all_ids.native_record_owns(semantic.native_ref.as_str()) {
                super::record_finding(
                    findings,
                    Check::NativeLinks,
                    Severity::Error,
                    Some(parameter.id.as_str()),
                    format_args!("PMI native_ref `{}` does not resolve", semantic.native_ref),
                );
            }
        }
    }
    for configuration in &ir.model.configurations {
        if let Some(target) = &configuration.native_ref {
            if !all_ids.native_record_owns(target.as_str()) {
                super::record_finding(
                    findings,
                    Check::NativeLinks,
                    Severity::Error,
                    Some(configuration.id.as_str()),
                    format_args!("native_ref `{target}` does not resolve"),
                );
            }
        }
    }
    for sketch in &ir.model.sketches {
        if let Some(target) = &sketch.native_ref {
            if !all_ids.native_record_owns(target.as_str()) {
                super::record_finding(
                    findings,
                    Check::NativeLinks,
                    Severity::Error,
                    Some(sketch.id.as_str()),
                    format_args!("native_ref `{target}` does not resolve"),
                );
            }
        }
    }
    for sketch in &ir.model.spatial_sketches {
        if let Some(target) = &sketch.native_ref {
            if !all_ids.native_record_owns(target.as_str()) {
                super::record_finding(
                    findings,
                    Check::NativeLinks,
                    Severity::Error,
                    Some(sketch.id.as_str()),
                    format_args!("native_ref `{target}` does not resolve"),
                );
            }
        }
    }
    for constraint in &ir.model.sketch_constraints {
        if let Some(target) = &constraint.native_ref {
            if !all_ids.native_record_owns(target.as_str()) {
                super::record_finding(
                    findings,
                    Check::NativeLinks,
                    Severity::Error,
                    Some(constraint.id.as_str()),
                    format_args!("native_ref `{target}` does not resolve"),
                );
            }
        }
        if let crate::sketches::SketchConstraintDefinitionInput::Native { operands, .. } =
            constraint.definition.kind()
        {
            for operand in operands {
                if let Some(target) = &operand.native_ref {
                    if !all_ids.native_record_owns(target.as_str()) {
                        super::record_finding(
                            findings,
                            Check::NativeLinks,
                            Severity::Error,
                            Some(constraint.id.as_str()),
                            format_args!("operand native_ref `{target}` does not resolve"),
                        );
                    }
                }
            }
        }
    }
    for constraint in &ir.model.spatial_sketch_constraints {
        if let Some(target) = &constraint.native_ref {
            if !all_ids.native_record_owns(target.as_str()) {
                super::record_finding(
                    findings,
                    Check::NativeLinks,
                    Severity::Error,
                    Some(constraint.id.as_str()),
                    format_args!("native_ref `{target}` does not resolve"),
                );
            }
        }
        if let crate::sketches::SpatialSketchConstraintDefinitionInput::Native {
            operands, ..
        } = constraint.definition.kind()
        {
            for operand in operands {
                if let Some(target) = &operand.native_ref {
                    if !all_ids.native_record_owns(target.as_str()) {
                        super::record_finding(
                            findings,
                            Check::NativeLinks,
                            Severity::Error,
                            Some(constraint.id.as_str()),
                            format_args!("operand native_ref `{target}` does not resolve"),
                        );
                    }
                }
            }
        }
    }

    // `unknowns` has a shared identity-link contract. Other arenas own their
    // field shapes; only an array made entirely of strings follows the generic
    // identity-link convention.
    view.for_each(|_, arena, records| {
        for entity in records.records() {
            let NativeEntity::Product(record) = entity else {
                for target in entity.links() {
                    if !all_ids.contains(&target, crate::index::StandardIndex) {
                        super::record_finding(
                            findings,
                            Check::NativeLinks,
                            Severity::Error,
                            Some(entity.id()),
                            format_args!("native-record link `{target}` does not resolve"),
                        );
                    }
                }
                continue;
            };

            let Some(value) = record.field("links") else {
                continue;
            };

            if arena != "unknowns"
                && !value
                    .as_array()
                    .is_some_and(|links| links.iter().all(serde_json::Value::is_string))
            {
                continue;
            }
            let serde_json::Value::Array(links) = value else {
                super::record_finding(
                    findings,
                    Check::NativeLinks,
                    Severity::Error,
                    Some(record.id()),
                    format_args!("{}", "native-record links must be an array of identities"),
                );
                continue;
            };
            for (index, link) in links.iter().enumerate() {
                let Some(target) = link.as_str() else {
                    super::record_finding(
                        findings,
                        Check::NativeLinks,
                        Severity::Error,
                        Some(record.id()),
                        format_args!("native-record link {index} must be an identity string"),
                    );
                    continue;
                };
                if !all_ids.contains(target, crate::index::StandardIndex) {
                    super::record_finding(
                        findings,
                        Check::NativeLinks,
                        Severity::Error,
                        Some(record.id()),
                        format_args!("native-record link `{target}` does not resolve"),
                    );
                }
            }
        }
    });
}

#[cfg(test)]
mod tests;