| // Copyright 2026 The Fuchsia Authors | |
| // | |
| // Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 | |
| // <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT | |
| // license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. | |
| // This file may not be copied, modified, or distributed except according to | |
| // those terms. | |
| //! Structured, fail-closed diagnostics and report rendering. | |
| use std::fmt::{self, Write as _}; | |
| use serde::Serialize; | |
| /// Parse or schema failure before semantic FFI checking can complete. | |
| #[derive(Debug, Clone, PartialEq, Eq)] | |
| pub enum ParseError { | |
| /// Invalid JSON syntax. | |
| Json(String), | |
| /// Missing required field, wrong type, or unsupported schema version. | |
| Schema(String), | |
| /// Malformed `rustc -Z print-type-sizes` input. | |
| TypeSizes(String), | |
| } | |
| impl fmt::Display for ParseError { | |
| fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
| match self { | |
| ParseError::Json(msg) => write!(f, "JSON parse error: {msg}"), | |
| ParseError::Schema(msg) => write!(f, "schema error: {msg}"), | |
| ParseError::TypeSizes(msg) => { | |
| write!(f, "print-type-sizes parse error: {msg}") | |
| } | |
| } | |
| } | |
| } | |
| impl std::error::Error for ParseError {} | |
| /// High-level FFI invariant category. | |
| #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] | |
| #[serde(rename_all = "snake_case")] | |
| pub enum DiagnosticCategory { | |
| TargetPolicy, | |
| AggregateGeometry, | |
| Padding, | |
| ScalarAndEnum, | |
| CallingConvention, | |
| UnwindAndObjectModel, | |
| CrossCheck, | |
| } | |
| /// Stable machine-readable diagnostic identifier. | |
| #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] | |
| #[serde(rename_all = "SCREAMING_SNAKE_CASE")] | |
| pub enum DiagnosticCode { | |
| TargetTripleMismatch, | |
| PointerWidthMismatch, | |
| CCharSignednessMismatch, | |
| CLongWidthMismatch, | |
| ReprNotC, | |
| MissingCppRecord, | |
| AmbiguousCppRecord, | |
| SizeMismatch, | |
| AlignMismatch, | |
| PackedMismatch, | |
| UnionMismatch, | |
| BitfieldUnsupported, | |
| FieldCountMismatch, | |
| FieldOffsetMismatch, | |
| FieldSizeMismatch, | |
| FieldTypeMismatch, | |
| InteriorPaddingExposed, | |
| TailPaddingExposed, | |
| PaddingOverlapsValue, | |
| BoolU8Conflation, | |
| IntWidthMismatch, | |
| IntSignednessMismatch, | |
| EnumWidthMismatch, | |
| EnumSignednessMismatch, | |
| EnumValidityUnverified, | |
| EnumTypeMismatch, | |
| EnumDiscriminantMismatch, | |
| PointerMutOrNullMismatch, | |
| ConstConsistencyViolation, | |
| ArrayLenMismatch, | |
| UnsupportedType, | |
| MissingCppFunction, | |
| NotExternC, | |
| CxxMethodAsExternC, | |
| CallingConvMismatch, | |
| VariadicMismatch, | |
| UnprototypedDeclaration, | |
| ExportDefinedInCpp, | |
| ParamCountMismatch, | |
| AbiPassingMismatch, | |
| ExtendSignMismatch, | |
| MissingAbiField, | |
| UnwindAbiMismatch, | |
| PolymorphicRecordByValue, | |
| NonTrivialDtorByValue, | |
| NonTriviallyCopyableByValue, | |
| CxxBasesUnsupported, | |
| PrintTypeSizesMismatch, | |
| } | |
| /// Stable machine-readable non-fatal warning identifier. | |
| #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] | |
| #[serde(rename_all = "SCREAMING_SNAKE_CASE")] | |
| pub enum WarningCode { | |
| /// An exported Rust function takes a parameter with extra validity | |
| /// invariants (`bool`, field-less `enum`, or non-null reference/pointer) | |
| /// that C callers must uphold. | |
| ExportValidityObligation, | |
| } | |
| /// One non-fatal FFI disclosure warning (does not fail ABI parity checks). | |
| #[derive(Debug, Clone, PartialEq, Eq, Serialize)] | |
| pub struct Warning { | |
| pub code: WarningCode, | |
| pub subject: String, | |
| pub message: String, | |
| /// Explicit non-omission caveat noting that non-flagged parameters still | |
| /// carry baseline byte-initialization validity obligations. | |
| pub baseline_validity_caveat: String, | |
| } | |
| /// One fail-closed FFI violation. | |
| #[derive(Debug, Clone, PartialEq, Eq, Serialize)] | |
| pub struct Diagnostic { | |
| pub code: DiagnosticCode, | |
| pub category: DiagnosticCategory, | |
| pub subject: String, | |
| pub message: String, | |
| pub remediation: String, | |
| } | |
| /// Classification of a contiguous padding span inside a C/C++ record. | |
| #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] | |
| #[serde(rename_all = "snake_case")] | |
| pub enum PaddingKind { | |
| Interior, | |
| Tail, | |
| } | |
| /// How a C/C++ padding span is accounted for on the Rust side. | |
| #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] | |
| #[serde(rename_all = "snake_case")] | |
| pub enum PaddingResolution { | |
| CoveredByMaybeUninit, | |
| DeclaredUnread, | |
| Exposed, | |
| } | |
| /// Explicit report of a detected padding byte range `[start_byte, end_byte)`. | |
| #[derive(Debug, Clone, PartialEq, Eq, Serialize)] | |
| pub struct PaddingRegionReport { | |
| pub record: String, | |
| pub kind: PaddingKind, | |
| pub start_byte: u64, | |
| pub end_byte: u64, | |
| pub resolution: PaddingResolution, | |
| } | |
| /// Complete FFI parity verification report. | |
| #[derive(Debug, Clone, PartialEq, Eq, Serialize)] | |
| pub struct CheckReport { | |
| pub schema_version: u32, | |
| pub ok: bool, | |
| pub target_triple: String, | |
| pub records_checked: usize, | |
| pub enums_checked: usize, | |
| pub functions_checked: usize, | |
| pub padding_regions: Vec<PaddingRegionReport>, | |
| pub diagnostics: Vec<Diagnostic>, | |
| #[serde(default, skip_serializing_if = "Vec::is_empty")] | |
| pub warnings: Vec<Warning>, | |
| } | |
| impl CheckReport { | |
| /// Renders the report as pretty-printed deterministic JSON. | |
| pub fn to_json_pretty(&self) -> Result<String, serde_json::Error> { | |
| serde_json::to_string_pretty(self) | |
| } | |
| /// Renders a concise human-readable diagnostic report. | |
| pub fn format_human(&self) -> String { | |
| let mut out = String::new(); | |
| let status = if self.ok { "PASS" } else { "FAIL" }; | |
| let _ = writeln!( | |
| out, | |
| "anneal-ffi-check: {status} (target={}, records={}, enums={}, \ | |
| functions={}, violations={})", | |
| self.target_triple, | |
| self.records_checked, | |
| self.enums_checked, | |
| self.functions_checked, | |
| self.diagnostics.len(), | |
| ); | |
| if !self.padding_regions.is_empty() { | |
| let _ = writeln!(out, "padding regions:"); | |
| for p in &self.padding_regions { | |
| let kind = match p.kind { | |
| PaddingKind::Interior => "interior", | |
| PaddingKind::Tail => "tail", | |
| }; | |
| let res = match p.resolution { | |
| PaddingResolution::CoveredByMaybeUninit => "covered(MaybeUninit<u8>)", | |
| PaddingResolution::DeclaredUnread => "declared_unread", | |
| PaddingResolution::Exposed => "EXPOSED", | |
| }; | |
| let _ = writeln!( | |
| out, | |
| " - {} [{}..{}) ({kind}): {res}", | |
| p.record, p.start_byte, p.end_byte, | |
| ); | |
| } | |
| } | |
| for (idx, d) in self.diagnostics.iter().enumerate() { | |
| let _ = | |
| writeln!(out, "error[{}] ({:?}) {}: {}", idx + 1, d.code, d.subject, d.message,); | |
| let _ = writeln!(out, " fix: {}", d.remediation); | |
| } | |
| for (idx, w) in self.warnings.iter().enumerate() { | |
| let _ = | |
| writeln!(out, "warning[{}] ({:?}) {}: {}", idx + 1, w.code, w.subject, w.message); | |
| let _ = writeln!(out, " note: {}", w.baseline_validity_caveat); | |
| } | |
| out | |
| } | |
| } |