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
// SPDX-License-Identifier: Apache-2.0
//! Interfaces for detecting, inspecting, decoding, and encoding CAD formats.
//!
//! [`Codec`] is object-safe for runtime codec registries. Detection consumes a
//! byte prefix, inspection summarizes a seekable container, and decoding
//! produces a finalized [`CadIr`] plus a [`DecodeReport`].
//!
//! A codec implements only the required [`CodecBackend`] methods. The public
//! [`Codec::inspect`] and [`Codec::decode`] entry points are the
//! single enforcement point for root-input limits and session finalize checks;
//! they live on the sealed [`Codec`] trait, blanket-implemented for every
//! [`CodecBackend`], so a codec cannot override an entry point and drop the
//! enforcement.

use std::fmt;

use crate::document::CadIr;
use crate::report::{
    check::Finding,
    decode::{Coverage, DecodeReport, DecodeTransfer, TransferLedger},
    loss::{LossNote as DecodeLoss, StrictConsequence},
};
use crate::source_fidelity::SourceFidelity;
use crate::ContainerSummary;
use cadmpeg_core::decode::{
    DecodeArena, DecodeContext, DecodeMode, DecodePolicy, InspectOptions, View,
};
use cadmpeg_core::dialect::FormatIdentity;
use cadmpeg_core::{CodecError, ReadSeek};
#[cfg(feature = "schema")]
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

/// The stable registry format namespace of one codec, as a typed value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FormatId(&'static str);

impl FormatId {
    /// Builds the format id for a registry namespace word.
    #[must_use]
    pub const fn new(namespace: &'static str) -> Self {
        Self(namespace)
    }

    /// The registry namespace word.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        self.0
    }
}

impl fmt::Display for FormatId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.pad(self.0)
    }
}

/// How confident a codec is that it can handle a given byte prefix.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum Confidence {
    /// Definitely not this format.
    No,
    /// Weak signal, such as a generic container signature.
    Low,
    /// Plausible but not conclusive.
    Medium,
    /// Strong, format-specific signal.
    High,
}

impl fmt::Display for Confidence {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::No => "no",
            Self::Low => "low",
            Self::Medium => "medium",
            Self::High => "high",
        })
    }
}

/// Options controlling source decoding.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct DecodeOptions {
    /// Stop after the container layer; do not attempt entity decode.
    pub container_only: bool,
    /// Resource limits and failure-handling mode governing the decode.
    #[serde(default)]
    pub policy: DecodePolicy,
}

/// A decoded document plus its loss report.
///
/// The sealed [`Codec`] wrapper constructs this value after it stamps the source
/// classification onto the report and finalizes the IR and source fidelity.
/// `#[non_exhaustive]` blocks external struct literals so callers cannot skip
/// finalization. Read through [`Self::ir`] and [`Self::report`]. Consume with
/// [`Self::into_parts`] to obtain the source fidelity or edit either document.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct DecodeResult {
    ir: CadIr,
    report: DecodeReport,
    source_fidelity: SourceFidelity,
}

/// A strict-policy refusal bound to the loss in its completed decode report.
///
/// Only the sealed decode wrapper constructs this value. The refusing loss is
/// therefore always an element of [`Self::report`].
#[derive(Debug)]
pub struct StrictDecodeRejection {
    report: Box<DecodeReport>,
    loss_index: usize,
}

#[derive(Debug, Clone, Copy)]
struct RejectingLossIndex(usize);

impl StrictDecodeRejection {
    fn new(report: DecodeReport, loss_index: RejectingLossIndex) -> Self {
        Self {
            report: Box::new(report),
            loss_index: loss_index.0,
        }
    }

    /// Returns the loss that caused the strict-policy refusal.
    #[must_use]
    pub fn loss(&self) -> &DecodeLoss {
        &self.report.losses[self.loss_index]
    }

    /// Returns the completed report that contains the refusing loss.
    #[must_use]
    pub fn report(&self) -> &DecodeReport {
        &self.report
    }
}

impl fmt::Display for StrictDecodeRejection {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let loss = self.loss();
        write!(f, "{}: {}", loss.code, loss.message)
    }
}

/// Failure from the policy-enforcing decode entry point.
///
/// Backend and resource failures remain [`CodecError`] values. A strict-policy
/// refusal is separate because decoding completed and produced a report; the
/// caller must be able to serialize that evidence even though no document is
/// admitted.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum DecodeFailure {
    /// The codec or decode context failed before a result was produced.
    #[error(transparent)]
    Codec(#[from] CodecError),
    /// Strict mode rejected the first loss whose floor requires refusal.
    #[error("strict mode rejects {rejection}")]
    StrictRejected {
        /// The completed report and its refusing loss.
        rejection: StrictDecodeRejection,
    },
}

/// What a backend returns from [`CodecBackend::decode_impl`].
///
/// Source identity is authored once, in `ir.source`. The sealed wrapper stamps
/// that classification onto the report; a backend cannot describe the document
/// and its report with two different identities.
#[derive(Debug, Clone, PartialEq)]
pub struct Decoded {
    /// The decoded document, with its source metadata authored by the backend.
    pub ir: CadIr,
    /// The report without classification.
    pub body: DecodeBody,
    /// Decode-time annotations and retained source records.
    pub source_fidelity: SourceFidelity,
}

/// A [`DecodeReport`] without its classification.
#[derive(Debug, Clone, PartialEq)]
pub struct DecodeBody {
    /// The backend transfer outcome.
    pub transfer: DecodeTransfer,
    /// Coverage measures keyed by their declared name.
    pub coverage: Coverage,
    /// Losses resolved during decoding.
    pub losses: Vec<DecodeLoss>,
    /// Codec-defined informational notes.
    pub notes: Vec<String>,
    /// Complete source-to-result accounting.
    pub transfer_ledger: TransferLedger,
}

impl DecodeBody {
    /// An empty body with the given transfer outcome.
    #[must_use]
    pub fn new(transfer: DecodeTransfer) -> Self {
        Self {
            transfer,
            coverage: Coverage::default(),
            losses: Vec::new(),
            notes: Vec::new(),
            transfer_ledger: TransferLedger::default(),
        }
    }
}

impl DecodeResult {
    /// Builds a result by stamping the document's source classification onto
    /// the report body, then canonicalizing the IR and source fidelity.
    ///
    /// A document without source metadata yields an unclassified report for
    /// `format`, the codec's registry format.
    fn new(
        decoded: Decoded,
        format: FormatId,
        container_only: bool,
        ctx: &DecodeContext<'_>,
    ) -> Result<Self, CodecError> {
        let Decoded {
            mut ir,
            body,
            source_fidelity,
        } = decoded;
        let classification = match ir.source.as_ref() {
            Some(source) => match source.classification() {
                FormatIdentity::Classified { dialects } => FormatIdentity::classified(
                    dialects.try_clone_for_decode(ctx, "decode result classification")?,
                ),
                FormatIdentity::Unclassified { format } => FormatIdentity::unclassified(
                    ctx.copy_retained_text(format, "decode result classification")?,
                ),
            },
            None => FormatIdentity::unclassified(
                ctx.copy_retained_text(format.as_str(), "decode result classification")?,
            ),
        };
        ir.finalize(ctx)?;
        Ok(Self {
            ir,
            report: DecodeReport::from_body(classification, body, container_only),
            source_fidelity,
        })
    }

    /// Borrow the finalized IR.
    pub fn ir(&self) -> &CadIr {
        &self.ir
    }

    /// Borrow the transfer report.
    pub fn report(&self) -> &DecodeReport {
        &self.report
    }

    /// Consume into IR, report, and source fidelity.
    pub fn into_parts(self) -> (CadIr, DecodeReport, SourceFidelity) {
        (self.ir, self.report, self.source_fidelity)
    }
}

/// Decoder and container inspector for one source format.
pub trait CodecBackend {
    /// Registry format namespace this codec decodes, e.g. `"f3d"`.
    ///
    /// The sealed wrapper reports it as [`Codec::id`] and refuses any result
    /// whose primary format names another namespace.
    const FORMAT: FormatId;

    /// Findings this codec's own validator reports over its native
    /// namespace on a decoded document.
    ///
    /// The default reports nothing, for a codec that writes no native
    /// namespace or has no validator for it. The sealed wrapper exposes it as
    /// [`Codec::validate_native`], which the application runs after
    /// `validate_neutral`.
    fn validate_native(_ctx: &DecodeContext<'_>, _ir: &CadIr) -> Result<Vec<Finding>, CodecError> {
        Ok(Vec::new())
    }

    /// Judge, from a leading byte prefix, whether this codec applies.
    fn detect_impl(
        &self,
        ctx: &DecodeContext<'_>,
        prefix: View<'_>,
    ) -> Result<Confidence, CodecError>;

    /// Enumerate the acquired root view's streams/segments without decoding
    /// geometry.
    ///
    /// Implemented by each codec; never called by the CLI or registry. The
    /// [`Codec::inspect`] wrapper acquires the root under the inspection's
    /// input limit and runs this under an internal context.
    fn inspect_impl(
        &self,
        ctx: &DecodeContext<'_>,
        root: View<'_>,
    ) -> Result<ContainerSummary, CodecError>;

    /// Decode the acquired root view, reporting incomplete or approximate
    /// transfer.
    ///
    /// Implemented by each codec; never called by the CLI or registry. The
    /// [`Codec::decode`] wrapper acquires the root and finalizes the
    /// context around this call.
    fn decode_impl(&self, ctx: &DecodeContext<'_>, root: View<'_>) -> Result<Decoded, CodecError>;
}

mod sealed {
    /// Private bound for the blanket [`Codec`](super::Codec) implementation.
    pub trait Sealed {}
    impl<C: super::CodecBackend + ?Sized> Sealed for C {}
}

/// Public inspection and decoding entry points.
///
/// ```compile_fail
/// use cadmpeg_ir::codec::{
///     Codec, CodecBackend, Confidence, DecodeOptions, DecodeResult, Decoded, FormatId,
/// };
/// use cadmpeg_core::{CodecError, ReadSeek};
/// use cadmpeg_core::decode::{DecodeContext, View};
/// use cadmpeg_core::decode::InspectOptions;
/// use cadmpeg_ir::ContainerSummary;
///
/// struct Rogue;
/// impl CodecBackend for Rogue {
///     const FORMAT: FormatId = FormatId::new("rogue");
///     fn detect_impl(&self, _: &DecodeContext<'_>, _: View<'_>) -> Result<Confidence, CodecError> { Ok(Confidence::No) }
///     fn inspect_impl(&self, _: &DecodeContext<'_>, _: View<'_>)
///         -> Result<ContainerSummary, CodecError> { panic!("never runs") }
///     fn decode_impl(&self, _: &DecodeContext<'_>, _: View<'_>)
///         -> Result<Decoded, CodecError> { panic!("never runs") }
/// }
/// impl Codec for Rogue {
///     fn id(&self) -> FormatId { FormatId::new("rogue") }
///     fn detect(&self, _: &DecodeContext<'_>, _: View<'_>) -> Result<Confidence, CodecError> { Ok(Confidence::No) }
///     fn validate_native(&self, _: &DecodeContext<'_>, _: &cadmpeg_ir::CadIr)
///         -> Result<Vec<cadmpeg_ir::report::check::Finding>, CodecError> {
///         Ok(Vec::new())
///     }
///     fn inspect(&self, _: &mut dyn ReadSeek, _: &InspectOptions)
///         -> Result<ContainerSummary, CodecError> { panic!("never runs") }
///     fn decode(&self, _: &mut dyn ReadSeek, _: &DecodeOptions)
///         -> Result<DecodeResult, cadmpeg_ir::codec::DecodeFailure> {
///         panic!("never runs")
///     }
/// }
/// ```
pub trait Codec: sealed::Sealed {
    /// Registry format namespace, [`CodecBackend::FORMAT`].
    fn id(&self) -> FormatId;

    /// Judge, from a leading byte prefix, whether this codec applies.
    fn detect(&self, ctx: &DecodeContext<'_>, prefix: View<'_>) -> Result<Confidence, CodecError>;

    /// Findings this codec reports over its own native namespace,
    /// [`CodecBackend::validate_native`].
    fn validate_native(
        &self,
        ctx: &DecodeContext<'_>,
        ir: &CadIr,
    ) -> Result<Vec<Finding>, CodecError>;

    /// Inspects the source under its input and resource limits.
    fn inspect(
        &self,
        reader: &mut dyn ReadSeek,
        options: &InspectOptions,
    ) -> Result<ContainerSummary, CodecError>;

    /// Decodes the source under its input and resource limits.
    ///
    /// [`DecodeMode::Strict`] refuses the decode with
    /// [`DecodeFailure::StrictRejected`] for the first reported loss whose
    /// [`StrictConsequence`] is [`StrictConsequence::Reject`]. The gate
    /// evaluates full-decode reports only: a container-only decode keeps its
    /// losses and is never refused. This gate owns the refusal predicate and
    /// the refusal class for every codec. A backend reports its losses with
    /// their strict floors and adds no strict gate of its own; a local gate
    /// widens the predicate and reclassifies the refusal without the caller
    /// seeing it.
    fn decode(
        &self,
        reader: &mut dyn ReadSeek,
        options: &DecodeOptions,
    ) -> Result<DecodeResult, DecodeFailure>;

    /// Decodes an acquired root in the caller's detection session.
    /// The caller finishes the session after this method returns.
    fn decode_with_context(
        &self,
        ctx: &DecodeContext<'_>,
        root: View<'_>,
        options: &DecodeOptions,
    ) -> Result<DecodeResult, DecodeFailure>;
}

impl<C: CodecBackend + ?Sized> Codec for C {
    fn id(&self) -> FormatId {
        C::FORMAT
    }

    fn detect(&self, ctx: &DecodeContext<'_>, prefix: View<'_>) -> Result<Confidence, CodecError> {
        self.detect_impl(ctx, prefix)
    }

    fn validate_native(
        &self,
        ctx: &DecodeContext<'_>,
        ir: &CadIr,
    ) -> Result<Vec<Finding>, CodecError> {
        C::validate_native(ctx, ir)
    }

    fn inspect(
        &self,
        reader: &mut dyn ReadSeek,
        options: &InspectOptions,
    ) -> Result<ContainerSummary, CodecError> {
        let arena = DecodeArena::new();
        let policy = DecodePolicy {
            mode: DecodeMode::Salvage,
            limits: options.limits,
        };
        let (ctx, root) = DecodeContext::read_root(reader, &arena, &policy, false)?;
        let result = self.inspect_impl(&ctx, root);
        ctx.finish_session()?;
        let result = result?;
        if result.format() != C::FORMAT.as_str() {
            return Err(CodecError::WrongFormat(format!(
                "codec {:?} inspected a {:?} container",
                C::FORMAT.as_str(),
                result.format()
            )));
        }
        Ok(result)
    }

    fn decode(
        &self,
        reader: &mut dyn ReadSeek,
        options: &DecodeOptions,
    ) -> Result<DecodeResult, DecodeFailure> {
        let arena = DecodeArena::new();
        let (ctx, root) =
            DecodeContext::read_root(reader, &arena, &options.policy, options.container_only)?;
        let result = self.decode_with_context(&ctx, root, options);
        ctx.finish_session()?;
        result
    }

    fn decode_with_context(
        &self,
        ctx: &DecodeContext<'_>,
        root: View<'_>,
        options: &DecodeOptions,
    ) -> Result<DecodeResult, DecodeFailure> {
        let decoded = self.decode_impl(ctx, root)?;
        let result = DecodeResult::new(decoded, C::FORMAT, options.container_only, ctx)?;
        if result.report().format() != C::FORMAT.as_str() {
            return Err(CodecError::WrongFormat(ctx.format_retained(
                format_args!(
                    "codec {:?} decoded a {:?} document",
                    C::FORMAT.as_str(),
                    result.report().format()
                ),
                "decode format refusal",
            )?)
            .into());
        }
        crate::validate::evaluation_cycles::admit_evaluation_cycles(ctx, result.ir())?;
        let strict_loss_index =
            if options.policy.mode == DecodeMode::Strict && !options.container_only {
                ctx.charge_work(
                    cadmpeg_core::decode::u64_from_index(result.report().losses.len()),
                    "decode strict loss scan",
                )?;
                result
                    .report()
                    .losses
                    .iter()
                    .position(|loss| loss.strict_consequence() == StrictConsequence::Reject)
                    .map(RejectingLossIndex)
            } else {
                None
            };
        if let Some(loss_index) = strict_loss_index {
            let (_, report, _) = result.into_parts();
            ctx.charge_retained(
                cadmpeg_core::decode::u64_from_index(std::mem::size_of::<DecodeReport>()),
                "decode strict rejection report",
            )?;
            let rejection = StrictDecodeRejection::new(report, loss_index);
            return Err(DecodeFailure::StrictRejected { rejection });
        }
        Ok(result)
    }
}

pub mod write;

#[cfg(test)]
mod tests;