1use diagprint::{
26 Cause, DiagnosticRelationship, DiagnosticRelationshipError, DiagnosticRelationshipEvidence,
27 DiagnosticRelationshipGraph, DiagnosticRelationshipKind, DiagnosticReport, DocumentationLink,
28 IDENTITY_ATTRIBUTE, InteropDiagnostic, InteropLabel, Reporter, Severity,
29};
30use std::{
31 error::Error,
32 fmt,
33 sync::atomic::{AtomicU64, Ordering},
34};
35
36const MAX_IDENTITY_LEN: usize = 256;
37const MAX_PRODUCER_LEN: usize = 64;
38
39static NEXT_BUILDER_SCOPE: AtomicU64 = AtomicU64::new(1);
40
41#[derive(Debug, Clone)]
47pub struct BridgeDiagnosticMetadata {
48 diagnostic: InteropDiagnostic,
49 identity: Option<String>,
50}
51
52impl BridgeDiagnosticMetadata {
53 pub fn new(message: impl Into<String>) -> Self {
54 Self {
55 diagnostic: InteropDiagnostic::new(message),
56 identity: None,
57 }
58 }
59
60 pub fn from_interop(diagnostic: InteropDiagnostic) -> Self {
61 Self {
62 diagnostic,
63 identity: None,
64 }
65 }
66
67 pub fn severity(mut self, severity: Severity) -> Self {
68 self.diagnostic = self.diagnostic.severity(severity);
69 self
70 }
71
72 pub fn code(mut self, code: impl Into<String>) -> Self {
73 self.diagnostic = self.diagnostic.code(code);
74 self
75 }
76
77 pub fn help(mut self, help: impl Into<String>) -> Self {
78 self.diagnostic = self.diagnostic.help(help);
79 self
80 }
81
82 pub fn note(mut self, note: impl Into<String>) -> Self {
83 self.diagnostic = self.diagnostic.note(note);
84 self
85 }
86
87 pub fn label(mut self, label: InteropLabel) -> Self {
88 self.diagnostic = self.diagnostic.label(label);
89 self
90 }
91
92 pub fn cause(mut self, cause: Cause) -> Self {
93 self.diagnostic = self.diagnostic.cause(cause);
94 self
95 }
96
97 pub fn documentation(mut self, link: DocumentationLink) -> Self {
98 self.diagnostic = self.diagnostic.documentation(link);
99 self
100 }
101
102 pub fn related(mut self, diagnostic: InteropDiagnostic) -> Self {
103 self.diagnostic = self.diagnostic.related(diagnostic);
104 self
105 }
106
107 pub fn identity(mut self, identity: impl Into<String>) -> Result<Self, BridgeError> {
113 let identity = identity.into();
114 validate_identity(&identity)?;
115 self.identity = Some(identity);
116 Ok(self)
117 }
118
119 pub fn interop(&self) -> &InteropDiagnostic {
120 &self.diagnostic
121 }
122
123 pub fn identity_value(&self) -> Option<&str> {
124 self.identity.as_deref()
125 }
126
127 fn into_diagprint(self, reporter: &Reporter) -> diagprint::Diagnostic {
128 let mut diagnostic = self.diagnostic.to_diagprint(reporter);
129
130 if let Some(identity) = self.identity {
131 diagnostic = diagnostic.attribute(IDENTITY_ATTRIBUTE, identity);
132 }
133
134 diagnostic
135 }
136}
137
138#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
144pub struct BridgeNodeId {
145 scope: u64,
146 index: usize,
147}
148
149#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
151pub struct BridgeBuildStats {
152 pub diagnostic_instances: usize,
153 pub logical_nodes: usize,
154 pub relationships: usize,
155 pub collapsed_self_relationships: usize,
156}
157
158#[derive(Debug)]
160pub struct BridgeOutput {
161 report: DiagnosticReport,
162 graph: DiagnosticRelationshipGraph,
163 stats: BridgeBuildStats,
164}
165
166impl BridgeOutput {
167 pub fn report(&self) -> &DiagnosticReport {
168 &self.report
169 }
170
171 pub fn graph(&self) -> &DiagnosticRelationshipGraph {
172 &self.graph
173 }
174
175 pub const fn stats(&self) -> BridgeBuildStats {
176 self.stats
177 }
178
179 pub fn into_parts(
180 self,
181 ) -> (
182 DiagnosticReport,
183 DiagnosticRelationshipGraph,
184 BridgeBuildStats,
185 ) {
186 (self.report, self.graph, self.stats)
187 }
188}
189
190pub struct BridgeOutputBuilder<'a> {
194 reporter: &'a Reporter,
195 producer: String,
196 scope: u64,
197 report: DiagnosticReport,
198 fingerprints: Vec<String>,
199 relationships: Vec<DiagnosticRelationship>,
200 collapsed_self_relationships: usize,
201}
202
203impl<'a> BridgeOutputBuilder<'a> {
204 pub fn new(reporter: &'a Reporter, producer: impl Into<String>) -> Result<Self, BridgeError> {
205 let producer = producer.into();
206 validate_producer(&producer)?;
207
208 Ok(Self {
209 reporter,
210 producer,
211 scope: next_builder_scope(),
212 report: DiagnosticReport::new(),
213 fingerprints: Vec::new(),
214 relationships: Vec::new(),
215 collapsed_self_relationships: 0,
216 })
217 }
218
219 pub fn producer(&self) -> &str {
220 &self.producer
221 }
222
223 pub fn push(
226 &mut self,
227 metadata: BridgeDiagnosticMetadata,
228 ) -> Result<BridgeNodeId, BridgeError> {
229 if let Some(identity) = metadata.identity_value() {
230 validate_identity(identity)?;
231 }
232
233 let diagnostic = metadata.into_diagprint(self.reporter);
234 let fingerprint = diagnostic.fingerprint().qualified();
235
236 let index = self.fingerprints.len();
237 self.fingerprints.push(fingerprint);
238 self.report.push(diagnostic);
239
240 Ok(BridgeNodeId {
241 scope: self.scope,
242 index,
243 })
244 }
245
246 pub fn relate(
251 &mut self,
252 from: BridgeNodeId,
253 to: BridgeNodeId,
254 kind: DiagnosticRelationshipKind,
255 evidence: DiagnosticRelationshipEvidence,
256 ) -> Result<&mut Self, BridgeError> {
257 let from_fingerprint = self.resolve(from)?.to_owned();
258 let to_fingerprint = self.resolve(to)?.to_owned();
259
260 if from_fingerprint == to_fingerprint {
261 self.collapsed_self_relationships = self.collapsed_self_relationships.saturating_add(1);
262 return Ok(self);
263 }
264
265 self.relationships.push(DiagnosticRelationship::new(
266 from_fingerprint,
267 to_fingerprint,
268 kind,
269 evidence,
270 self.producer.clone(),
271 )?);
272
273 Ok(self)
274 }
275
276 pub fn finish(self) -> Result<BridgeOutput, BridgeError> {
278 let graph = DiagnosticRelationshipGraph::from_report(&self.report, self.relationships)?;
279
280 let stats = BridgeBuildStats {
281 diagnostic_instances: self.report.len(),
282 logical_nodes: graph.node_count(),
283 relationships: graph.edge_count(),
284 collapsed_self_relationships: self.collapsed_self_relationships,
285 };
286
287 Ok(BridgeOutput {
288 report: self.report,
289 graph,
290 stats,
291 })
292 }
293
294 fn resolve(&self, node: BridgeNodeId) -> Result<&str, BridgeError> {
295 if node.scope != self.scope {
296 return Err(BridgeError::ForeignNode {
297 expected_scope: self.scope,
298 actual_scope: node.scope,
299 });
300 }
301
302 self.fingerprints
303 .get(node.index)
304 .map(String::as_str)
305 .ok_or(BridgeError::UnknownNode {
306 index: node.index,
307 len: self.fingerprints.len(),
308 })
309 }
310}
311
312fn next_builder_scope() -> u64 {
313 loop {
314 let scope = NEXT_BUILDER_SCOPE.fetch_add(1, Ordering::Relaxed);
315
316 if scope != 0 {
317 return scope;
318 }
319 }
320}
321
322fn validate_identity(value: &str) -> Result<(), BridgeError> {
323 let valid = !value.is_empty()
324 && value.len() <= MAX_IDENTITY_LEN
325 && !value.chars().any(char::is_control);
326
327 if valid {
328 Ok(())
329 } else {
330 Err(BridgeError::InvalidIdentity {
331 value: value.to_owned(),
332 })
333 }
334}
335
336fn validate_producer(value: &str) -> Result<(), BridgeError> {
337 let valid = !value.is_empty()
338 && value.len() <= MAX_PRODUCER_LEN
339 && value
340 .bytes()
341 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'));
342
343 if valid {
344 Ok(())
345 } else {
346 Err(BridgeError::InvalidProducer {
347 value: value.to_owned(),
348 })
349 }
350}
351
352#[derive(Debug)]
353pub enum BridgeError {
354 InvalidIdentity {
355 value: String,
356 },
357 InvalidProducer {
358 value: String,
359 },
360 ForeignNode {
361 expected_scope: u64,
362 actual_scope: u64,
363 },
364 UnknownNode {
365 index: usize,
366 len: usize,
367 },
368 Relationship(DiagnosticRelationshipError),
369}
370
371impl fmt::Display for BridgeError {
372 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
373 match self {
374 Self::InvalidIdentity { value } => {
375 write!(formatter, "invalid bridge logical identity {value:?}")
376 }
377 Self::InvalidProducer { value } => {
378 write!(formatter, "invalid bridge producer {value:?}")
379 }
380 Self::ForeignNode {
381 expected_scope,
382 actual_scope,
383 } => write!(
384 formatter,
385 "bridge node belongs to another builder scope: expected {expected_scope}, got {actual_scope}"
386 ),
387 Self::UnknownNode { index, len } => write!(
388 formatter,
389 "bridge node index {index} is out of range for {len} diagnostic instance(s)"
390 ),
391 Self::Relationship(source) => {
392 write!(
393 formatter,
394 "bridge relationship construction failed: {source}"
395 )
396 }
397 }
398 }
399}
400
401impl Error for BridgeError {
402 fn source(&self) -> Option<&(dyn Error + 'static)> {
403 match self {
404 Self::Relationship(source) => Some(source),
405 _ => None,
406 }
407 }
408}
409
410impl From<DiagnosticRelationshipError> for BridgeError {
411 fn from(source: DiagnosticRelationshipError) -> Self {
412 Self::Relationship(source)
413 }
414}