Skip to main content

ifc_model/
diagnostic.rs

1//! Codec-neutral, non-fatal problems found while reading a model.
2//!
3//! A codec that recovers from damaged input must be able to say what it
4//! dropped: silent recovery turns a corrupt file into a plausible-looking
5//! model with no trace of the loss. These diagnostics are attached to the
6//! [`Model`](crate::Model) rather than returned separately so the information
7//! survives being passed around an application.
8//!
9//! The type is codec-neutral on purpose. STEP reports byte offsets, ifcXML
10//! would report element positions, so the location is an optional byte range
11//! rather than a STEP span, and this crate names no codec type.
12
13use std::fmt;
14use std::ops::Range;
15
16use crate::EntityId;
17
18mod damage;
19
20pub use damage::{RecordDamage, UnclassifiedDiagnostic};
21
22/// How serious a non-fatal finding is.
23#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
24#[non_exhaustive]
25pub enum Severity {
26    /// Input was read, but not fully represented — something was dropped.
27    #[default]
28    Warning,
29}
30
31/// What a [`Diagnostic`] is about, for a caller that acts on it instead of
32/// printing it.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
34#[non_exhaustive]
35pub enum DiagnosticKind {
36    /// A record was dropped because it was malformed or unrepresentable.
37    SkippedRecord,
38    /// Two records declared the same id.
39    DuplicateId,
40    /// A record references an id no record declares.
41    DanglingReference,
42    /// A real number was written without a decimal point.
43    RealWithoutPoint,
44    /// Anything else, including findings built by [`Diagnostic::warning`].
45    Other,
46}
47
48/// A line and column in the source text, both 1-based.
49///
50/// The column counts Unicode characters of the line before the position.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
52pub struct SourcePosition {
53    line: usize,
54    column: usize,
55}
56
57impl SourcePosition {
58    /// A position at a 1-based line and column.
59    pub const fn new(line: usize, column: usize) -> Self {
60        Self { line, column }
61    }
62
63    /// 1-based line number.
64    pub const fn line(&self) -> usize {
65        self.line
66    }
67
68    /// 1-based column, counted in characters.
69    pub const fn column(&self) -> usize {
70        self.column
71    }
72}
73
74impl fmt::Display for SourcePosition {
75    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
76        write!(formatter, "line {}, column {}", self.line, self.column)
77    }
78}
79
80/// A non-fatal problem found while reading a model.
81#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct Diagnostic {
83    severity: Severity,
84    kind: DiagnosticKind,
85    byte_range: Option<Range<usize>>,
86    position: Option<SourcePosition>,
87    instance: Option<EntityId>,
88    referrer: Option<EntityId>,
89    excerpt: Option<String>,
90    detail: String,
91}
92
93impl Diagnostic {
94    /// Records a warning of `kind` with no source location; add one with the
95    /// `with_*` builders.
96    pub fn new(kind: DiagnosticKind, detail: impl Into<String>) -> Self {
97        Self {
98            severity: Severity::Warning,
99            kind,
100            byte_range: None,
101            position: None,
102            instance: None,
103            referrer: None,
104            excerpt: None,
105            detail: detail.into(),
106        }
107    }
108
109    /// Records a [`DiagnosticKind::Other`] warning covering a byte range of
110    /// the source.
111    pub fn warning(byte_range: Range<usize>, detail: impl Into<String>) -> Self {
112        Self::new(DiagnosticKind::Other, detail).with_byte_range(byte_range)
113    }
114
115    /// Records a [`DiagnosticKind::Other`] warning with no source location.
116    pub fn unlocated(detail: impl Into<String>) -> Self {
117        Self::new(DiagnosticKind::Other, detail)
118    }
119
120    /// Sets the byte range of the source this finding covers.
121    #[must_use]
122    pub fn with_byte_range(mut self, range: Range<usize>) -> Self {
123        self.byte_range = Some(range);
124        self
125    }
126
127    /// Sets the line and column where the finding starts.
128    #[must_use]
129    pub fn with_position(mut self, position: SourcePosition) -> Self {
130        self.position = Some(position);
131        self
132    }
133
134    /// Sets the instance at fault: a skipped record's id, the duplicated id
135    /// or the missing id of a dangling reference.
136    #[must_use]
137    pub fn with_instance(mut self, id: EntityId) -> Self {
138        self.instance = Some(id);
139        self
140    }
141
142    /// Sets the record holding a dangling reference.
143    #[must_use]
144    pub fn with_referrer(mut self, id: EntityId) -> Self {
145        self.referrer = Some(id);
146        self
147    }
148
149    /// Sets a short quote of the source this finding covers.
150    #[must_use]
151    pub fn with_excerpt(mut self, excerpt: impl Into<String>) -> Self {
152        self.excerpt = Some(excerpt.into());
153        self
154    }
155
156    /// Severity of this finding.
157    pub const fn severity(&self) -> Severity {
158        self.severity
159    }
160
161    /// What this finding is about.
162    pub const fn kind(&self) -> DiagnosticKind {
163        self.kind
164    }
165
166    /// Byte range of the source this finding covers, when the codec has one.
167    pub const fn byte_range(&self) -> Option<&Range<usize>> {
168        self.byte_range.as_ref()
169    }
170
171    /// The instance at fault: a skipped record's id when it was read, the
172    /// duplicated id, or the missing id of a dangling reference. `None` for
173    /// [`DiagnosticKind::RealWithoutPoint`] and [`DiagnosticKind::Other`].
174    pub const fn instance(&self) -> Option<EntityId> {
175        self.instance
176    }
177
178    /// The record holding the reference, for a
179    /// [`DiagnosticKind::DanglingReference`] only.
180    pub const fn referrer(&self) -> Option<EntityId> {
181        self.referrer
182    }
183
184    /// Line and column where the finding starts, when the codec has one.
185    pub const fn position(&self) -> Option<SourcePosition> {
186        self.position
187    }
188
189    /// A short quote of the source this finding covers.
190    pub fn excerpt(&self) -> Option<&str> {
191        self.excerpt.as_deref()
192    }
193
194    /// Human-readable description without a location prefix.
195    pub fn detail(&self) -> &str {
196        &self.detail
197    }
198}
199
200impl fmt::Display for Diagnostic {
201    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
202        match (&self.position, &self.byte_range) {
203            (Some(position), Some(range)) => write!(
204                formatter,
205                "warning at {position} (bytes {}..{}): {}",
206                range.start, range.end, self.detail
207            ),
208            (Some(position), None) => {
209                write!(formatter, "warning at {position}: {}", self.detail)
210            }
211            (None, Some(range)) => write!(
212                formatter,
213                "warning at bytes {}..{}: {}",
214                range.start, range.end, self.detail
215            ),
216            (None, None) => write!(formatter, "warning: {}", self.detail),
217        }
218    }
219}