cadmpeg-codec-sat 0.6.2

Inspect and decode bare ASM .sat/.sab/.smt/.smb B-rep streams.
Documentation
// SPDX-License-Identifier: Apache-2.0
//! Stable loss vocabulary for SAT/ASM stream decoding.
//!
//! Every fallback, approximation, and drop the decoder reports carries a
//! stable machine-readable code from [`SatLossCode`]. Codes are the gating
//! surface: harness oracles and downstream tooling key on them, never on the
//! human-readable message text, so a reworded message is not a contract change
//! and a new drop path without a code does not compile.
//!
//! [`SatLossCode::note`] is the single practical construction path for a
//! decode-time [`LossNote`] in this crate: it fixes the loss category and
//! severity from the code so the two cannot drift apart across sites, and it
//! leaves only the per-instance message to the caller.
//!
use cadmpeg_ir::report::{
    loss::{LossKind, LossNamespace, LossNote, LossTaxonomy},
    Severity,
};

const NAMESPACE: LossNamespace<'static> = match LossNamespace::new("sat") {
    Ok(namespace) => namespace,
    Err(_) => panic!("reserved codec namespace"),
};

/// A stable, machine-readable identifier for one SAT/ASM transfer loss.
///
/// Variants are grouped by the record family whose transfer degraded. The
/// string form (via [`SatLossCode::code`]) is the stable contract.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) enum SatLossCode {
    /// The stream framed but decoded no surfaces, points, or faces.
    GeometryFramedWithoutCarriers,
    /// A face rests on a procedural surface construction without a decoded carrier.
    GeometryProceduralSurfaceUntyped,
    /// A tolerant-coedge use curve has decreasing carrier endpoints.
    GeometryUseCurveIntervalInvalid,
    /// A tolerant vertex has no positive finite evaluated tolerance.
    VertexToleranceUnresolved,
    /// Tolerant-edge tolerance cannot enter the positive neutral scalar.
    EdgeToleranceUnresolved,
    /// A shell has no admissible member or owner.
    TopologyShellUnprojected,
    /// A standalone source face has no shell owner required by the IR.
    TopologyFaceOwnerUnprojected,
    /// A body-owned source wire cannot use the IR's shell ownership.
    TopologyWireOwnerUnprojected,
    /// A framed record has no leading source-name component.
    SourceRecordNameUnresolved,
    /// ACIS record extensions are retained without neutral projection.
    SourceRecordExtensionsUnprojected,
    /// A header tolerance cannot supply a positive finite document tolerance.
    HeaderToleranceUnresolved,
    /// Independently framed product metadata is malformed.
    HeaderMetadataNoncanonical,
    /// The stream declares no usable length unit; lengths are read unscaled as
    /// millimetres.
    HeaderLengthUnitUnresolved,
    /// The input ends without a terminator line after its last complete record.
    FramingTerminatorMissing,
    /// Bytes after the last framed record were not read as records.
    FramingRecordsUnread,
    /// The stream was read with a grammar its own save-format declaration does
    /// not select.
    SourceDialectUnverified,
    /// Independently headed text streams have separate local reference tables.
    SourceConcatenatedStreamsRecovered,
    /// A later text stream has an unreadable or different native record layout.
    SourceStreamLayoutUnprojected,
}

impl SatLossCode {
    /// Every code, in declaration order.
    #[cfg(test)]
    const ALL: &'static [SatLossCode] = &[
        Self::GeometryFramedWithoutCarriers,
        Self::GeometryProceduralSurfaceUntyped,
        Self::GeometryUseCurveIntervalInvalid,
        Self::VertexToleranceUnresolved,
        Self::EdgeToleranceUnresolved,
        Self::TopologyShellUnprojected,
        Self::TopologyFaceOwnerUnprojected,
        Self::TopologyWireOwnerUnprojected,
        Self::SourceRecordNameUnresolved,
        Self::SourceRecordExtensionsUnprojected,
        Self::HeaderToleranceUnresolved,
        Self::HeaderMetadataNoncanonical,
        Self::HeaderLengthUnitUnresolved,
        Self::FramingTerminatorMissing,
        Self::FramingRecordsUnread,
        Self::SourceDialectUnverified,
        Self::SourceConcatenatedStreamsRecovered,
        Self::SourceStreamLayoutUnprojected,
    ];

    /// The stable string identifier. This is the gating contract.
    #[must_use]
    const fn code(self) -> &'static str {
        match self {
            Self::GeometryFramedWithoutCarriers => "geometry.framed-without-carriers",
            Self::GeometryProceduralSurfaceUntyped => "geometry.procedural-surface-untyped",
            Self::GeometryUseCurveIntervalInvalid => "geometry.use-curve-interval-invalid",
            Self::VertexToleranceUnresolved => "vertex.tolerance-unresolved",
            Self::EdgeToleranceUnresolved => "edge.tolerance-unresolved",
            Self::TopologyShellUnprojected => "topology.shell-unprojected",
            Self::TopologyFaceOwnerUnprojected => "topology.face-owner-unprojected",
            Self::TopologyWireOwnerUnprojected => "topology.wire-owner-unprojected",
            Self::SourceRecordNameUnresolved => "source.record-name-unresolved",
            Self::SourceRecordExtensionsUnprojected => "source.record-extensions-unprojected",
            Self::HeaderToleranceUnresolved => "header.tolerance-unresolved",
            Self::HeaderMetadataNoncanonical => "header.metadata-noncanonical",
            Self::HeaderLengthUnitUnresolved => "header.length-unit-unresolved",
            Self::FramingTerminatorMissing => "framing.terminator-missing",
            Self::FramingRecordsUnread => "framing.records-unread",
            Self::SourceDialectUnverified => "source.kernel-dialect-unverified",
            Self::SourceConcatenatedStreamsRecovered => "source.concatenated-streams-recovered",
            Self::SourceStreamLayoutUnprojected => "source.stream-layout-unprojected",
        }
    }

    /// The severity of this loss.
    #[must_use]
    const fn severity(self) -> Severity {
        match self {
            Self::GeometryFramedWithoutCarriers => Severity::Blocking,
            Self::GeometryProceduralSurfaceUntyped
            | Self::GeometryUseCurveIntervalInvalid
            | Self::EdgeToleranceUnresolved
            | Self::VertexToleranceUnresolved
            | Self::TopologyShellUnprojected
            | Self::TopologyFaceOwnerUnprojected
            | Self::TopologyWireOwnerUnprojected
            | Self::SourceRecordNameUnresolved
            | Self::SourceRecordExtensionsUnprojected
            | Self::HeaderToleranceUnresolved
            | Self::HeaderMetadataNoncanonical
            | Self::HeaderLengthUnitUnresolved
            | Self::FramingTerminatorMissing
            | Self::FramingRecordsUnread
            | Self::SourceDialectUnverified
            | Self::SourceConcatenatedStreamsRecovered
            | Self::SourceStreamLayoutUnprojected => Severity::Warning,
        }
    }

    const fn shared_taxonomy(self) -> LossTaxonomy {
        match self {
            Self::GeometryFramedWithoutCarriers
            | Self::GeometryProceduralSurfaceUntyped
            | Self::HeaderToleranceUnresolved
            | Self::GeometryUseCurveIntervalInvalid
            | Self::EdgeToleranceUnresolved
            | Self::VertexToleranceUnresolved
            | Self::TopologyShellUnprojected
            | Self::TopologyFaceOwnerUnprojected
            | Self::TopologyWireOwnerUnprojected
            | Self::HeaderLengthUnitUnresolved
            | Self::FramingRecordsUnread
            | Self::SourceStreamLayoutUnprojected => LossTaxonomy::GeometryNotTransferred,
            Self::SourceDialectUnverified => LossTaxonomy::SourceDialectUnverified,
            Self::SourceRecordExtensionsUnprojected => LossTaxonomy::GeometryNotTransferred,
            Self::SourceConcatenatedStreamsRecovered
            | Self::HeaderMetadataNoncanonical
            | Self::FramingTerminatorMissing
            | Self::SourceRecordNameUnresolved => LossTaxonomy::NoncanonicalSourceSyntax,
        }
    }

    /// Namespaced [`LossKind`] for this local code, classified by taxonomy.
    #[must_use]
    pub(crate) fn kind(self) -> LossKind {
        LossKind::namespaced(NAMESPACE, self.code(), self.shared_taxonomy())
    }

    /// Build a [`LossNote`] for this code with the given per-instance message.
    ///
    /// The structured code is `sat/<local>`. Severity comes from the local
    /// code; the strict floor comes from the taxonomy.
    #[must_use]
    pub(crate) fn note(self, message: impl Into<String>) -> LossNote {
        LossNote::new(self.kind(), message).with_severity(self.severity())
    }
}

/// Project shared text-stream recovery into codec losses for decode and inspection.
pub(crate) fn text_stream_losses<'a>(
    diagnostics: impl IntoIterator<Item = &'a cadmpeg_asm::sat::StreamDiagnostic>,
    unread_layout_offset: Option<usize>,
    losses: &mut Vec<LossNote>,
) {
    use cadmpeg_asm::sat::StreamDiagnosticKind;
    for diagnostic in diagnostics {
        let code = match diagnostic.kind {
            StreamDiagnosticKind::Metadata => SatLossCode::HeaderMetadataNoncanonical,
            StreamDiagnosticKind::Tolerance => SatLossCode::HeaderToleranceUnresolved,
            StreamDiagnosticKind::Units => SatLossCode::HeaderLengthUnitUnresolved,
            StreamDiagnosticKind::Terminator => SatLossCode::FramingTerminatorMissing,
            StreamDiagnosticKind::Unread
                if unread_layout_offset == Some(diagnostic.error.offset) =>
            {
                SatLossCode::SourceStreamLayoutUnprojected
            }
            StreamDiagnosticKind::Unread => SatLossCode::FramingRecordsUnread,
        };
        let message = format!(
            "byte {}: {}; independent records retained",
            diagnostic.error.offset, diagnostic.error.reason
        );
        losses.push(
            code.note(message)
                .with_provenance(cadmpeg_ir::SourceProvenance::root(
                    "sat",
                    cadmpeg_core::decode::u64_from_index(diagnostic.error.offset),
                )),
        );
    }
}

/// Diagnose product payloads independently of their binary byte boundaries.
pub(crate) fn binary_header_losses(
    header: &cadmpeg_asm::kernel_header::KernelHeader,
    losses: &mut Vec<LossNote>,
) {
    for field in header.unreadable_product_fields() {
        losses.push(SatLossCode::HeaderMetadataNoncanonical.note(format!(
            "binary header {field} is unreadable; independent records retained"
        )));
    }
}

#[cfg(test)]
mod tests {
    use super::SatLossCode;
    use std::collections::BTreeSet;

    /// Value-level golden: the stable string form of every code, pinned.
    #[test]
    fn code_strings_are_pinned() {
        let codes: Vec<&str> = SatLossCode::ALL.iter().map(|c| c.code()).collect();
        assert_eq!(
            codes,
            [
                "geometry.framed-without-carriers",
                "geometry.procedural-surface-untyped",
                "geometry.use-curve-interval-invalid",
                "vertex.tolerance-unresolved",
                "edge.tolerance-unresolved",
                "topology.shell-unprojected",
                "topology.face-owner-unprojected",
                "topology.wire-owner-unprojected",
                "source.record-name-unresolved",
                "source.record-extensions-unprojected",
                "header.tolerance-unresolved",
                "header.metadata-noncanonical",
                "header.length-unit-unresolved",
                "framing.terminator-missing",
                "framing.records-unread",
                "source.kernel-dialect-unverified",
                "source.concatenated-streams-recovered",
                "source.stream-layout-unprojected",
            ]
        );
    }

    /// Codes are unique and use the stable `family.detail` kebab shape.
    #[test]
    fn codes_are_unique_and_well_formed() {
        let mut seen = BTreeSet::new();
        for code in SatLossCode::ALL {
            let text = code.code();
            assert!(seen.insert(text), "duplicate code {text}");
            let (family, detail) = text.split_once('.').expect("family.detail shape");
            assert!(!family.is_empty() && !detail.is_empty());
            assert!(
                text.bytes()
                    .all(|b| b.is_ascii_lowercase() || b == b'.' || b == b'-'),
                "code {text} is not lowercase kebab"
            );
        }
    }

    /// The note builder fixes severity from the codec-specific code.
    #[test]
    fn note_takes_severity_from_the_code() {
        for code in SatLossCode::ALL {
            let note = code.note("x");
            assert_eq!(note.severity, code.severity());
            assert_eq!(note.message, "x");
            assert!(note.provenance.is_none());
        }
    }
}