cadmpeg-ir 0.6.1

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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
// SPDX-License-Identifier: Apache-2.0
//! Decode reports, coverage, and source-transfer disposition.

use std::collections::BTreeMap;

use cadmpeg_core::dialect::{DialectLayers, FormatIdentity};
#[cfg(feature = "schema")]
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::report::loss::LossNote;

/// Transfer status and loss details from a successful decode.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(into = "DecodeReportWire", from = "DecodeReportWire")]
#[serde(deny_unknown_fields)]
pub struct DecodeReport {
    classification: FormatIdentity<DialectLayers>,
    transfer: DecodeTransfer,
    /// Decode coverage counts keyed by declared measure name.
    coverage: Coverage,
    /// Explicit loss notes.
    pub losses: Vec<LossNote>,
    /// Free-form informational notes (e.g. container findings).
    pub notes: Vec<String>,
    /// Per-source disposition ledger for decoded records and entities.
    pub transfer_ledger: TransferLedger,
}

/// Mutually exclusive source-transfer states for a decode report.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "transfer", rename_all = "snake_case", deny_unknown_fields)]
#[non_exhaustive]
pub enum DecodeTransfer {
    /// The request stopped after container inspection and transferred no
    /// semantic geometry.
    ContainerOnly {},
    /// The request ran the full decoder, with the recorded B-rep geometry
    /// outcome.
    Full {
        /// Whether B-rep geometry was transferred into the IR.
        geometry_transferred: bool,
    },
}

impl DecodeTransfer {
    /// Constructs the state for a full decode with its geometry outcome.
    #[must_use]
    pub const fn full(geometry_transferred: bool) -> Self {
        Self::Full {
            geometry_transferred,
        }
    }

    /// Constructs the transfer state from the sealed wrapper's request scope
    /// and the backend's geometry outcome.
    const fn stamp_request_scope(container_only: bool, transfer: Self) -> Self {
        if container_only {
            Self::ContainerOnly {}
        } else {
            Self::full(transfer.geometry_transferred())
        }
    }

    /// Returns whether the request stopped at the container layer.
    #[must_use]
    pub const fn container_only(self) -> bool {
        matches!(self, Self::ContainerOnly {})
    }

    /// Returns whether B-rep geometry was transferred into the IR.
    #[must_use]
    pub const fn geometry_transferred(self) -> bool {
        matches!(
            self,
            Self::Full {
                geometry_transferred: true
            }
        )
    }
}

#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct DecodeReportWire {
    /// Source format identity and its classified dialect layers.
    identity: FormatIdentity<DialectLayers>,
    /// Typed source-transfer state.
    transfer: DecodeTransfer,
    /// Decode coverage counts keyed by declared measure name.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    #[serde(deserialize_with = "cadmpeg_core::distinct_keys::btree_map")]
    coverage: BTreeMap<String, usize>,
    /// Explicit loss notes.
    losses: Vec<LossNote>,
    /// Free-form informational notes (e.g. container findings).
    notes: Vec<String>,
    /// Per-source disposition ledger for decoded records and entities.
    #[serde(default, skip_serializing_if = "TransferLedger::is_empty")]
    transfer_ledger: TransferLedger,
}

impl From<DecodeReport> for DecodeReportWire {
    fn from(report: DecodeReport) -> Self {
        let DecodeReport {
            classification,
            transfer,
            coverage,
            losses,
            notes,
            transfer_ledger,
        } = report;
        Self {
            identity: classification,
            transfer,
            coverage: coverage.into_wire(),
            losses,
            notes,
            transfer_ledger,
        }
    }
}

impl From<DecodeReportWire> for DecodeReport {
    fn from(wire: DecodeReportWire) -> Self {
        Self {
            classification: wire.identity,
            transfer: wire.transfer,
            coverage: Coverage::from_wire(wire.coverage),
            losses: wire.losses,
            notes: wire.notes,
            transfer_ledger: wire.transfer_ledger,
        }
    }
}

#[cfg(feature = "schema")]
impl JsonSchema for DecodeReport {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "DecodeReport".into()
    }

    fn schema_id() -> std::borrow::Cow<'static, str> {
        concat!(module_path!(), "::DecodeReport").into()
    }

    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        DecodeReportWire::json_schema(generator)
    }
}

/// Final disposition of one source record or semantic object.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum TransferDisposition {
    /// Transferred as an exact neutral or native entity.
    Emitted,
    /// Preserved in a native retained-record arena.
    Retained,
    /// Transferred with an explicit approximation.
    Approximated,
    /// Deliberately not transferred.
    Omitted,
}

/// One source object's structurally valid transfer outcome.
///
/// The disposition is the wire's tag, so each outcome carries exactly the
/// fields valid for it: an emitted record has no note to state, and an omitted
/// record has no target.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "disposition", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum TransferOutcome {
    /// Transferred as an exact neutral or native entity.
    Emitted {
        /// Resulting neutral or native identity.
        target: String,
    },
    /// Preserved in a native retained-record arena.
    Retained {
        /// Resulting native retained-record identity.
        target: String,
        /// Informational note about retention or semantic projection.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_note"
        )]
        note: Option<String>,
    },
    /// Transferred with an explicit approximation.
    Approximated {
        /// Resulting neutral or native identity.
        target: String,
        /// Concise reason for the approximation.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_note"
        )]
        note: Option<String>,
    },
    /// Deliberately not transferred.
    Omitted {
        /// Concise reason for the omission.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_note"
        )]
        note: Option<String>,
    },
}

/// One source object's transfer disposition.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct TransferRecord {
    /// Stable source identity or source-local record key.
    pub source: String,
    /// Outcome whose variant carries exactly the data valid for its disposition.
    pub outcome: TransferOutcome,
}

impl TransferRecord {
    /// Returns the produced target, or `None` for an omitted source object.
    #[must_use]
    pub fn target(&self) -> Option<&str> {
        match &self.outcome {
            TransferOutcome::Emitted { target }
            | TransferOutcome::Retained { target, .. }
            | TransferOutcome::Approximated { target, .. } => Some(target),
            TransferOutcome::Omitted { .. } => None,
        }
    }
}

/// Complete source-to-result accounting for a decode.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct TransferLedger {
    /// Entries in deterministic source traversal order.
    pub entries: Vec<TransferRecord>,
}

impl TransferLedger {
    /// Returns whether the ledger contains no transfer entries.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Records one source disposition.
    pub fn record(&mut self, source: impl Into<String>, outcome: TransferOutcome) {
        self.entries.push(TransferRecord {
            source: source.into(),
            outcome,
        });
    }

    /// Verifies every produced target against a finalized model index.
    pub fn verify(&self, index: &crate::index::ModelIndex<'_>) -> Result<(), String> {
        for entry in &self.entries {
            if let Some(target) = entry
                .target()
                .filter(|target| !index.contains(target, crate::index::StandardIndex))
            {
                return Err(format!(
                    "transfer source {:?} targets unresolved identity {:?}",
                    entry.source, target
                ));
            }
        }
        Ok(())
    }
}

/// A typed decode-coverage measure name.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CoverageKey(&'static str);

impl CoverageKey {
    /// Declares a coverage key with a static wire name.
    #[must_use]
    pub const fn new(name: &'static str) -> Self {
        Self(name)
    }

    /// Returns the coverage key's wire name.
    #[must_use]
    pub fn as_str(&self) -> &str {
        self.0
    }
}

/// A statically declared coverage-name template with one numeric component.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct IndexedCoverageKey {
    prefix: &'static str,
    suffix: &'static str,
}

/// A statically declared coverage-name template with one hexadecimal byte.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HexByteCoverageKey {
    prefix: &'static str,
    suffix: &'static str,
}

impl IndexedCoverageKey {
    /// Declares a coverage-name template whose index uses decimal notation.
    #[must_use]
    pub const fn decimal(prefix: &'static str, suffix: &'static str) -> Self {
        Self { prefix, suffix }
    }
}

impl HexByteCoverageKey {
    /// Declares a coverage-name template whose byte uses two lowercase
    /// hexadecimal digits.
    #[must_use]
    pub const fn new(prefix: &'static str, suffix: &'static str) -> Self {
        Self { prefix, suffix }
    }
}

/// Decode coverage whose entries can be written only through declared keys.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Coverage {
    entries: BTreeMap<String, usize>,
}

impl Coverage {
    /// Records a static key after admitting its new map node and retained name.
    pub fn record(
        &mut self,
        ctx: &cadmpeg_core::decode::DecodeContext<'_>,
        key: CoverageKey,
        count: usize,
    ) -> Result<(), cadmpeg_core::CodecError> {
        ctx.charge_work(1, "decode coverage lookup")?;
        if let Some(value) = self.entries.get_mut(key.0) {
            *value = count;
            return Ok(());
        }
        let name = ctx.copy_retained_text(key.0, "decode coverage names")?;
        self.insert_name(ctx, name, count)
    }

    /// Records a decimal-indexed key after admitting its temporary and retained name.
    pub fn record_indexed(
        &mut self,
        ctx: &cadmpeg_core::decode::DecodeContext<'_>,
        key: IndexedCoverageKey,
        index: u32,
        count: usize,
    ) -> Result<(), cadmpeg_core::CodecError> {
        let (name, bytes) = ctx.format_scoped(
            format_args!("{}{index}{}", key.prefix, key.suffix),
            "decode indexed coverage name",
        )?;
        ctx.charge_work(1, "decode coverage lookup")?;
        if let Some(value) = self.entries.get_mut(&name) {
            *value = count;
            return Ok(());
        }
        bytes.commit()?;
        self.insert_name(ctx, name, count)
    }

    /// Records a hexadecimal-byte key after admitting its temporary and retained name.
    pub fn record_hex_byte(
        &mut self,
        ctx: &cadmpeg_core::decode::DecodeContext<'_>,
        key: HexByteCoverageKey,
        value: u8,
        count: usize,
    ) -> Result<(), cadmpeg_core::CodecError> {
        let (name, bytes) = ctx.format_scoped(
            format_args!("{}{:02x}{}", key.prefix, value, key.suffix),
            "decode hexadecimal coverage name",
        )?;
        ctx.charge_work(1, "decode coverage lookup")?;
        if let Some(existing) = self.entries.get_mut(&name) {
            *existing = count;
            return Ok(());
        }
        bytes.commit()?;
        self.insert_name(ctx, name, count)
    }

    /// Records an already-copied declared key without allocating another key.
    ///
    /// The caller can reserve and charge the copy before calling this method.
    pub fn record_owned(
        &mut self,
        ctx: &cadmpeg_core::decode::DecodeContext<'_>,
        key: CoverageKey,
        name: String,
        count: usize,
    ) -> Result<(), cadmpeg_core::CodecError> {
        ctx.charge_work(
            cadmpeg_core::decode::u64_from_index(name.len()),
            "decode coverage name admission",
        )?;
        if name != key.0 {
            return Err(cadmpeg_core::CodecError::malformed(
                "coverage name does not match its declared key",
            ));
        }
        self.insert_name(ctx, name, count)
    }

    fn insert_name(
        &mut self,
        ctx: &cadmpeg_core::decode::DecodeContext<'_>,
        name: String,
        count: usize,
    ) -> Result<(), cadmpeg_core::CodecError> {
        ctx.charge_work(1, "decode coverage lookup")?;
        if let Some(value) = self.entries.get_mut(&name) {
            *value = count;
            return Ok(());
        }
        ctx.charge_work(1, "decode coverage nodes")?;
        ctx.insert_btree_map(&mut self.entries, name, count, "decode coverage nodes")?;
        Ok(())
    }

    /// Build a coverage map through the charged insertion operation.
    pub fn from_iter_for_decode(
        ctx: &cadmpeg_core::decode::DecodeContext<'_>,
        entries: impl IntoIterator<Item = (CoverageKey, usize)>,
    ) -> Result<Self, cadmpeg_core::CodecError> {
        let mut coverage = Self::default();
        for (key, count) in entries {
            coverage.record(ctx, key, count)?;
        }
        Ok(coverage)
    }

    /// Returns all recorded counts by their wire names.
    #[must_use]
    fn as_map(&self) -> &BTreeMap<String, usize> {
        &self.entries
    }

    fn from_wire(entries: BTreeMap<String, usize>) -> Self {
        Self { entries }
    }

    fn into_wire(self) -> BTreeMap<String, usize> {
        self.entries
    }
}

impl Extend<(CoverageKey, usize)> for Coverage {
    fn extend<T: IntoIterator<Item = (CoverageKey, usize)>>(&mut self, iter: T) {
        for (key, count) in iter {
            self.entries.insert(key.0.to_owned(), count);
        }
    }
}

impl FromIterator<(CoverageKey, usize)> for Coverage {
    fn from_iter<T: IntoIterator<Item = (CoverageKey, usize)>>(iter: T) -> Self {
        let mut coverage = Self::default();
        coverage.extend(iter);
        coverage
    }
}

impl std::ops::Deref for Coverage {
    type Target = BTreeMap<String, usize>;

    fn deref(&self) -> &Self::Target {
        self.as_map()
    }
}

impl DecodeReport {
    /// Stamps a classification onto a report body.
    ///
    /// The sealed decode wrapper is the production caller: the classification
    /// is the document's own source identity, authored once by the backend.
    #[must_use]
    pub(crate) fn from_body(
        classification: FormatIdentity<DialectLayers>,
        body: crate::codec::DecodeBody,
        container_only: bool,
    ) -> Self {
        Self {
            classification,
            transfer: DecodeTransfer::stamp_request_scope(container_only, body.transfer),
            coverage: body.coverage,
            losses: body.losses,
            notes: body.notes,
            transfer_ledger: body.transfer_ledger,
        }
    }

    /// Constructs a classified report whose format is its primary layer's format.
    #[must_use]
    #[cfg(test)]
    fn classified(
        dialects: DialectLayers,
        transfer: DecodeTransfer,
        coverage: BTreeMap<String, usize>,
        losses: Vec<LossNote>,
        notes: Vec<String>,
        transfer_ledger: TransferLedger,
    ) -> Self {
        Self {
            classification: FormatIdentity::classified(dialects),
            transfer,
            coverage: Coverage::from_wire(coverage),
            losses,
            notes,
            transfer_ledger,
        }
    }

    /// Constructs an unclassified report for a known source format.
    #[must_use]
    #[cfg(test)]
    pub(crate) fn unclassified(
        format: impl Into<String>,
        transfer: DecodeTransfer,
        coverage: BTreeMap<String, usize>,
        losses: Vec<LossNote>,
        notes: Vec<String>,
        transfer_ledger: TransferLedger,
    ) -> Self {
        Self {
            classification: FormatIdentity::unclassified(format),
            transfer,
            coverage: Coverage::from_wire(coverage),
            losses,
            notes,
            transfer_ledger,
        }
    }

    /// Returns the source format id.
    #[must_use]
    pub fn format(&self) -> &str {
        self.classification.format()
    }

    /// Returns the classified dialect layers, if decoding classified them.
    #[must_use]
    pub fn dialects(&self) -> Option<&DialectLayers> {
        self.classification.classified_payload()
    }

    /// Returns whether the decode stopped at the container layer.
    #[must_use]
    pub const fn container_only(&self) -> bool {
        self.transfer.container_only()
    }

    /// Returns whether B-rep geometry was transferred into the IR.
    #[must_use]
    pub const fn geometry_transferred(&self) -> bool {
        self.transfer.geometry_transferred()
    }
}

// Each optional key below names itself in whatever it refuses.
cadmpeg_core::named_optional_field!(deserialize_note, String, "note");

#[cfg(test)]
mod tests;