use serde::ser::SerializeMap;
use serde::{Serialize, Serializer};
use serde_json::{Map, Value};
use crate::generated::codes::{ErrorCode, WarningCode};
use crate::{ErrorKind, Location};
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Diagnostic {
pub code: String,
pub kind: ErrorKind,
pub message: String,
pub hint: Option<String>,
pub did_you_mean: Vec<String>,
pub location: Location,
pub data: Map<String, Value>,
pub docs_url: String,
}
impl Diagnostic {
#[must_use]
pub fn error(code: ErrorCode, message: impl Into<String>) -> Self {
Self::of(code.as_str(), code.kind(), message.into(), code.hint(), code.docs_url())
}
#[must_use]
pub fn warning(code: WarningCode) -> Self {
Self::of(
code.as_str(),
code.kind(),
code.summary().to_owned(),
code.hint(),
code.docs_url(),
)
}
fn of(code: &str, kind: ErrorKind, message: String, hint: &str, docs_url: String) -> Self {
Self {
code: code.to_owned(),
kind,
message,
hint: Some(hint.to_owned()),
did_you_mean: Vec::new(),
location: Location::NONE,
data: Map::new(),
docs_url,
}
}
#[must_use]
pub fn with_hint(mut self, hint: Option<String>) -> Self {
self.hint = hint;
self
}
#[must_use]
pub fn with_did_you_mean(mut self, did_you_mean: Vec<String>) -> Self {
self.did_you_mean = did_you_mean;
self
}
#[must_use]
pub fn with_location(mut self, location: Location) -> Self {
self.location = location;
self
}
#[must_use]
pub fn with_data(mut self, data: Map<String, Value>) -> Self {
self.data = data;
self
}
#[must_use]
pub fn to_json(&self) -> Value {
serde_json::to_value(self).unwrap_or(Value::Null)
}
}
impl Serialize for Diagnostic {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut map = serializer.serialize_map(None)?;
map.serialize_entry("code", &self.code)?;
map.serialize_entry("kind", self.kind.as_str())?;
map.serialize_entry("message", &self.message)?;
if let Some(hint) = &self.hint {
map.serialize_entry("hint", hint)?;
}
if !self.did_you_mean.is_empty() {
map.serialize_entry("didYouMean", &self.did_you_mean)?;
}
if !self.location.is_empty() {
map.serialize_entry("location", &LocationJson(&self.location))?;
}
if !self.data.is_empty() {
map.serialize_entry("data", &self.data)?;
}
map.serialize_entry("docsUrl", &self.docs_url)?;
map.end()
}
}
struct LocationJson<'a>(&'a Location);
impl Serialize for LocationJson<'_> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let l = self.0;
let mut map = serializer.serialize_map(None)?;
if let Some(offset) = l.offset {
map.serialize_entry("offset", &offset)?;
}
if let Some(object) = l.object {
map.serialize_entry("object", &object)?;
}
if let Some(offset) = l.stream_offset {
map.serialize_entry("streamOffset", &offset)?;
}
if let Some(index) = l.page_index {
map.serialize_entry("pageIndex", &index)?;
}
if let Some(id) = &l.id {
map.serialize_entry("id", id)?;
}
map.end()
}
}