use std::fmt;
use astrs_manifest::{Pattern, Urn};
use serde::{Deserialize, Serialize};
use crate::edge::EdgeKey;
use crate::ids::{NodeId, PortName};
use crate::pattern::PatternKind;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Severity {
Info,
Warning,
Error,
}
impl fmt::Display for Severity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Info => "info",
Self::Warning => "warning",
Self::Error => "error",
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum DiagnosticKind {
TypeMismatch {
edge: EdgeKey,
expected: Urn,
found: Urn,
},
Cycle {
nodes: Vec<NodeId>,
uncorrelated_edges: Vec<EdgeKey>,
},
UnpairedPatternNode {
node: NodeId,
pattern: Pattern,
},
PartialPatternPair {
client: NodeId,
server: NodeId,
kind: PatternKind,
has_request_edge: bool,
has_response_edge: bool,
},
UnconsumedOutput {
node: NodeId,
output: PortName,
},
OrphanedOutputType {
node: NodeId,
output: PortName,
},
OrphanedInputType {
node: NodeId,
input: PortName,
},
RecordSugarPortCollision {
node: NodeId,
port: PortName,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Diagnostic {
pub severity: Severity,
pub kind: DiagnosticKind,
}
impl Diagnostic {
#[must_use]
pub fn new(severity: Severity, kind: DiagnosticKind) -> Self {
Self { severity, kind }
}
#[must_use]
pub fn edge(&self) -> Option<&EdgeKey> {
match &self.kind {
DiagnosticKind::TypeMismatch { edge, .. } => Some(edge),
_ => None,
}
}
}
impl fmt::Display for Diagnostic {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "[{}] ", self.severity)?;
match &self.kind {
DiagnosticKind::TypeMismatch {
edge,
expected,
found,
} => write!(
f,
"type mismatch on {edge}: expected `{expected}`, found `{found}`"
),
DiagnosticKind::Cycle {
nodes,
uncorrelated_edges,
} => {
let node_list = nodes
.iter()
.map(NodeId::as_str)
.collect::<Vec<_>>()
.join(" -> ");
write!(
f,
"cycle among plain data edges: {node_list} (uncorrelated edges: {})",
uncorrelated_edges.len()
)
}
DiagnosticKind::UnpairedPatternNode { node, pattern } => {
write!(
f,
"node `{node}` declares pattern {pattern:?} but is not wired to a matching counterpart"
)
}
DiagnosticKind::PartialPatternPair {
client,
server,
kind,
has_request_edge,
has_response_edge,
} => write!(
f,
"{kind} pair `{client}` <-> `{server}` is only partially wired (request: {has_request_edge}, response: {has_response_edge})"
),
DiagnosticKind::UnconsumedOutput { node, output } => {
write!(f, "output `{output}` on node `{node}` has no consumer")
}
DiagnosticKind::OrphanedOutputType { node, output } => write!(
f,
"node `{node}` declares an output_types entry for `{output}`, which is not in its outputs list"
),
DiagnosticKind::OrphanedInputType { node, input } => write!(
f,
"node `{node}` declares an input_types entry for `{input}`, which is not in its inputs map"
),
DiagnosticKind::RecordSugarPortCollision { node, port } => write!(
f,
"node `{node}`'s record: sugar wants a synthetic port `{port}` that collides with an explicitly declared input; the declared input wins"
),
}
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
#[test]
fn severity_orders_info_below_warning_below_error() {
assert!(Severity::Info < Severity::Warning);
assert!(Severity::Warning < Severity::Error);
}
#[test]
fn diagnostic_edge_is_some_only_for_type_mismatch() {
let d = Diagnostic::new(
Severity::Error,
DiagnosticKind::TypeMismatch {
edge: EdgeKey::new(NodeId::new("detector"), PortName::new("frames")),
expected: Urn::new("std/media/v1/Image"),
found: Urn::new("std/vision/v1/Detections"),
},
);
assert!(d.edge().is_some());
let d2 = Diagnostic::new(
Severity::Info,
DiagnosticKind::UnconsumedOutput {
node: NodeId::new("camera"),
output: PortName::new("frames"),
},
);
assert!(d2.edge().is_none());
}
#[test]
fn diagnostic_display_includes_severity_tag() {
let d = Diagnostic::new(
Severity::Warning,
DiagnosticKind::UnconsumedOutput {
node: NodeId::new("camera"),
output: PortName::new("frames"),
},
);
let rendered = d.to_string();
assert!(rendered.starts_with("[warning]"), "was: {rendered}");
assert!(rendered.contains("camera"), "was: {rendered}");
}
#[test]
fn severity_display_is_lowercase() {
assert_eq!(Severity::Error.to_string(), "error");
assert_eq!(Severity::Warning.to_string(), "warning");
assert_eq!(Severity::Info.to_string(), "info");
}
}