use std::cmp::Ordering;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use crate::ir::SourceSpan;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum DiagnosticCode {
#[serde(rename = "invalid-markdown-include")]
InvalidMarkdownInclude,
#[serde(rename = "invalid-content-image")]
InvalidContentImage,
#[serde(rename = "duplicate-page-title")]
DuplicatePageTitle,
#[serde(rename = "invalid-component")]
InvalidComponent,
#[serde(rename = "unresolved-document-reference")]
UnresolvedDocumentReference,
#[serde(rename = "incompatible-package-relationship")]
IncompatiblePackageRelationship,
#[serde(rename = "indeterminate-package-relationship")]
IndeterminatePackageRelationship,
#[serde(rename = "conflicting-extraction")]
ConflictingExtraction,
#[serde(rename = "unsupported-extractor")]
UnsupportedExtractor,
#[serde(rename = "doxygen-extraction")]
DoxygenExtraction,
#[serde(rename = "doxygen-unsupported")]
DoxygenUnsupported,
#[serde(rename = "rust-metadata")]
RustMetadata,
#[serde(rename = "rust-source-read")]
RustSourceRead,
#[serde(rename = "rust-toolchain")]
RustToolchain,
#[serde(rename = "rust-extraction")]
RustExtraction,
#[serde(rename = "rust-unsupported-surface")]
RustUnsupportedSurface,
#[serde(rename = "rust-documentation")]
RustDocumentation,
#[serde(rename = "julia-metadata")]
JuliaMetadata,
#[serde(rename = "julia-source-read")]
JuliaSourceRead,
#[serde(rename = "julia-syntax")]
JuliaSyntax,
#[serde(rename = "julia-include")]
JuliaInclude,
#[serde(rename = "julia-unsupported-surface")]
JuliaUnsupportedSurface,
#[serde(rename = "julia-unresolved-definition")]
JuliaUnresolvedDefinition,
#[serde(rename = "julia-conflicting-surface")]
JuliaConflictingSurface,
#[serde(rename = "julia-unsupported-docstring")]
JuliaUnsupportedDocstring,
#[serde(rename = "julia-unsupported-markdown")]
JuliaUnsupportedMarkdown,
#[serde(rename = "unresolved-item-reference")]
UnresolvedItemReference,
#[serde(rename = "ambiguous-item-reference")]
AmbiguousItemReference,
#[serde(rename = "unsupported-kernel-message")]
UnsupportedKernelMessage,
#[serde(rename = "shadowed-kernelspec")]
ShadowedKernelspec,
#[serde(rename = "execution-startup-failed")]
ExecutionStartupFailed,
#[serde(rename = "execution-protocol-failed")]
ExecutionProtocolFailed,
#[serde(rename = "execution-input-requested")]
ExecutionInputRequested,
#[serde(rename = "execution-cell-failed")]
ExecutionCellFailed,
#[serde(rename = "execution-timeout")]
ExecutionTimeout,
#[serde(rename = "execution-cancelled")]
ExecutionCancelled,
#[serde(rename = "execution-cleanup-failed")]
ExecutionCleanupFailed,
#[serde(rename = "execution-output-failed")]
ExecutionOutputFailed,
#[serde(rename = "generated-asset-outside-boundary")]
GeneratedAssetOutsideBoundary,
#[serde(rename = "generated-asset-missing")]
GeneratedAssetMissing,
#[serde(rename = "execution-asset-collision")]
ExecutionAssetCollision,
#[serde(rename = "unsupported-cell-output")]
UnsupportedCellOutput,
#[serde(rename = "invalid-cell-output")]
InvalidCellOutput,
#[serde(rename = "unsafe-kernel-html")]
UnsafeKernelHtml,
#[serde(rename = "unsafe-kernel-svg")]
UnsafeKernelSvg,
#[serde(rename = "execution-input-changed")]
ExecutionInputChanged,
#[serde(rename = "invalid-execution-cache")]
InvalidExecutionCache,
#[serde(rename = "execution-cache-unavailable")]
ExecutionCacheUnavailable,
#[serde(rename = "non-deterministic-execution")]
NonDeterministicExecution,
#[serde(rename = "r-metadata")]
RMetadata,
#[serde(rename = "r-source-read")]
RSourceRead,
#[serde(rename = "r-library-unavailable")]
RLibraryUnavailable,
#[serde(rename = "r-syntax")]
RSyntax,
#[serde(rename = "r-unsupported-namespace")]
RUnsupportedNamespace,
#[serde(rename = "r-unresolved-definition")]
RUnresolvedDefinition,
#[serde(rename = "r-conflicting-surface")]
RConflictingSurface,
#[serde(rename = "r-missing-documented-alias")]
RMissingDocumentedAlias,
#[serde(rename = "r-unsupported-surface")]
RUnsupportedSurface,
#[serde(rename = "r-rd-syntax")]
RRdSyntax,
#[serde(rename = "r-rd-information-loss")]
RRdInformationLoss,
#[serde(rename = "r-rd-source-attribution")]
RRdSourceAttribution,
#[serde(rename = "unsupported-rd")]
UnsupportedRd,
#[serde(rename = "unsupported-authored-syntax")]
UnsupportedAuthoredSyntax,
#[serde(rename = "invalid-page-layout")]
InvalidPageLayout,
#[serde(rename = "invalid-embedded-yaml")]
InvalidEmbeddedYaml,
#[serde(rename = "ambiguous-cell-option")]
AmbiguousCellOption,
#[serde(rename = "unsupported-cell-option")]
UnsupportedCellOption,
#[serde(rename = "invalid-cell-option")]
InvalidCellOption,
#[serde(rename = "invalid-figure-options")]
InvalidFigureOptions,
#[serde(rename = "document-execution-not-authorized")]
DocumentExecutionNotAuthorized,
#[serde(rename = "unsupported-qmd-metadata")]
UnsupportedQmdMetadata,
#[serde(rename = "invalid-qmd-metadata")]
InvalidQmdMetadata,
#[serde(rename = "configuration-read-failed")]
ConfigurationReadFailed,
#[serde(rename = "invalid-configuration")]
InvalidConfiguration,
#[serde(rename = "invalid-execution-configuration")]
InvalidExecutionConfiguration,
#[serde(rename = "invalid-source-path")]
InvalidSourcePath,
#[serde(rename = "source-path-io")]
SourcePathIo,
#[serde(rename = "source-path-wrong-type")]
SourcePathWrongType,
#[serde(rename = "source-path-outside-boundary")]
SourcePathOutsideBoundary,
#[serde(rename = "invalid-repository-reference")]
InvalidRepositoryReference,
#[serde(rename = "duplicate-repository-id")]
DuplicateRepositoryId,
#[serde(rename = "duplicate-package-id")]
DuplicatePackageId,
#[serde(rename = "duplicate-target-id")]
DuplicateTargetId,
#[serde(rename = "duplicate-content-id")]
DuplicateContentId,
#[serde(rename = "duplicate-concept-id")]
DuplicateConceptId,
#[serde(rename = "duplicate-package-slug")]
DuplicatePackageSlug,
#[serde(rename = "unknown-content-owner")]
UnknownContentOwner,
#[serde(rename = "unknown-concept-package")]
UnknownConceptPackage,
#[serde(rename = "unknown-relationship-endpoint")]
UnknownRelationshipEndpoint,
#[serde(rename = "invalid-external-package-coordinate")]
InvalidExternalPackageCoordinate,
#[serde(rename = "python-metadata")]
PythonMetadata,
#[serde(rename = "python-dynamic-metadata")]
PythonDynamicMetadata,
#[serde(rename = "python-syntax")]
PythonSyntax,
#[serde(rename = "python-unsupported-version")]
PythonUnsupportedVersion,
#[serde(rename = "python-unsupported-syntax")]
PythonUnsupportedSyntax,
#[serde(rename = "python-source-read")]
PythonSourceRead,
#[serde(rename = "python-module-collision")]
PythonModuleCollision,
#[serde(rename = "python-dynamic-export")]
PythonDynamicExport,
#[serde(rename = "python-unresolved-reexport")]
PythonUnresolvedReexport,
#[serde(rename = "python-conflicting-stub")]
PythonConflictingStub,
#[serde(rename = "python-unsupported-surface")]
PythonUnsupportedSurface,
#[serde(rename = "python-duplicate-identity")]
PythonDuplicateIdentity,
#[serde(rename = "python-conflicting-alias")]
PythonConflictingAlias,
#[serde(rename = "python-invalid-identity")]
PythonInvalidIdentity,
#[serde(rename = "python-incomplete-docstring")]
PythonIncompleteDocstring,
#[serde(rename = "python-unsupported-docstring")]
PythonUnsupportedDocstring,
#[serde(rename = "python-docstring-source-attribution")]
PythonDocstringSourceAttribution,
}
impl DiagnosticCode {
pub const fn as_str(self) -> &'static str {
match self {
Self::DuplicatePageTitle => "duplicate-page-title",
Self::UnsupportedKernelMessage => "unsupported-kernel-message",
Self::ShadowedKernelspec => "shadowed-kernelspec",
Self::ExecutionStartupFailed => "execution-startup-failed",
Self::ExecutionProtocolFailed => "execution-protocol-failed",
Self::ExecutionInputRequested => "execution-input-requested",
Self::ExecutionCellFailed => "execution-cell-failed",
Self::ExecutionTimeout => "execution-timeout",
Self::ExecutionCancelled => "execution-cancelled",
Self::ExecutionCleanupFailed => "execution-cleanup-failed",
Self::ExecutionOutputFailed => "execution-output-failed",
Self::ConflictingExtraction => "conflicting-extraction",
Self::UnresolvedDocumentReference => "unresolved-document-reference",
Self::InvalidContentImage => "invalid-content-image",
Self::IncompatiblePackageRelationship => "incompatible-package-relationship",
Self::IndeterminatePackageRelationship => "indeterminate-package-relationship",
Self::UnsupportedExtractor => "unsupported-extractor",
Self::DoxygenExtraction => "doxygen-extraction",
Self::DoxygenUnsupported => "doxygen-unsupported",
Self::RustMetadata => "rust-metadata",
Self::RustSourceRead => "rust-source-read",
Self::RustToolchain => "rust-toolchain",
Self::RustExtraction => "rust-extraction",
Self::RustUnsupportedSurface => "rust-unsupported-surface",
Self::RustDocumentation => "rust-documentation",
Self::JuliaMetadata => "julia-metadata",
Self::JuliaSourceRead => "julia-source-read",
Self::JuliaSyntax => "julia-syntax",
Self::JuliaInclude => "julia-include",
Self::JuliaUnsupportedSurface => "julia-unsupported-surface",
Self::JuliaUnresolvedDefinition => "julia-unresolved-definition",
Self::JuliaConflictingSurface => "julia-conflicting-surface",
Self::JuliaUnsupportedDocstring => "julia-unsupported-docstring",
Self::JuliaUnsupportedMarkdown => "julia-unsupported-markdown",
Self::UnresolvedItemReference => "unresolved-item-reference",
Self::AmbiguousItemReference => "ambiguous-item-reference",
Self::GeneratedAssetOutsideBoundary => "generated-asset-outside-boundary",
Self::GeneratedAssetMissing => "generated-asset-missing",
Self::ExecutionAssetCollision => "execution-asset-collision",
Self::UnsupportedCellOutput => "unsupported-cell-output",
Self::InvalidCellOutput => "invalid-cell-output",
Self::UnsafeKernelHtml => "unsafe-kernel-html",
Self::UnsafeKernelSvg => "unsafe-kernel-svg",
Self::ExecutionInputChanged => "execution-input-changed",
Self::InvalidExecutionCache => "invalid-execution-cache",
Self::ExecutionCacheUnavailable => "execution-cache-unavailable",
Self::NonDeterministicExecution => "non-deterministic-execution",
Self::RMetadata => "r-metadata",
Self::RSourceRead => "r-source-read",
Self::RLibraryUnavailable => "r-library-unavailable",
Self::RSyntax => "r-syntax",
Self::RUnsupportedNamespace => "r-unsupported-namespace",
Self::RUnresolvedDefinition => "r-unresolved-definition",
Self::RConflictingSurface => "r-conflicting-surface",
Self::RMissingDocumentedAlias => "r-missing-documented-alias",
Self::RUnsupportedSurface => "r-unsupported-surface",
Self::RRdSyntax => "r-rd-syntax",
Self::RRdInformationLoss => "r-rd-information-loss",
Self::RRdSourceAttribution => "r-rd-source-attribution",
Self::UnsupportedRd => "unsupported-rd",
Self::InvalidMarkdownInclude => "invalid-markdown-include",
Self::InvalidComponent => "invalid-component",
Self::UnsupportedAuthoredSyntax => "unsupported-authored-syntax",
Self::InvalidEmbeddedYaml => "invalid-embedded-yaml",
Self::AmbiguousCellOption => "ambiguous-cell-option",
Self::UnsupportedCellOption => "unsupported-cell-option",
Self::InvalidCellOption => "invalid-cell-option",
Self::InvalidFigureOptions => "invalid-figure-options",
Self::DocumentExecutionNotAuthorized => "document-execution-not-authorized",
Self::UnsupportedQmdMetadata => "unsupported-qmd-metadata",
Self::InvalidQmdMetadata => "invalid-qmd-metadata",
Self::InvalidPageLayout => "invalid-page-layout",
Self::ConfigurationReadFailed => "configuration-read-failed",
Self::InvalidConfiguration => "invalid-configuration",
Self::InvalidExecutionConfiguration => "invalid-execution-configuration",
Self::InvalidSourcePath => "invalid-source-path",
Self::SourcePathIo => "source-path-io",
Self::SourcePathWrongType => "source-path-wrong-type",
Self::SourcePathOutsideBoundary => "source-path-outside-boundary",
Self::InvalidRepositoryReference => "invalid-repository-reference",
Self::DuplicateRepositoryId => "duplicate-repository-id",
Self::DuplicatePackageId => "duplicate-package-id",
Self::DuplicateTargetId => "duplicate-target-id",
Self::DuplicateContentId => "duplicate-content-id",
Self::DuplicateConceptId => "duplicate-concept-id",
Self::DuplicatePackageSlug => "duplicate-package-slug",
Self::UnknownContentOwner => "unknown-content-owner",
Self::UnknownConceptPackage => "unknown-concept-package",
Self::UnknownRelationshipEndpoint => "unknown-relationship-endpoint",
Self::InvalidExternalPackageCoordinate => "invalid-external-package-coordinate",
Self::PythonMetadata => "python-metadata",
Self::PythonDynamicMetadata => "python-dynamic-metadata",
Self::PythonSyntax => "python-syntax",
Self::PythonUnsupportedVersion => "python-unsupported-version",
Self::PythonUnsupportedSyntax => "python-unsupported-syntax",
Self::PythonSourceRead => "python-source-read",
Self::PythonModuleCollision => "python-module-collision",
Self::PythonDynamicExport => "python-dynamic-export",
Self::PythonUnresolvedReexport => "python-unresolved-reexport",
Self::PythonConflictingStub => "python-conflicting-stub",
Self::PythonUnsupportedSurface => "python-unsupported-surface",
Self::PythonDuplicateIdentity => "python-duplicate-identity",
Self::PythonConflictingAlias => "python-conflicting-alias",
Self::PythonInvalidIdentity => "python-invalid-identity",
Self::PythonIncompleteDocstring => "python-incomplete-docstring",
Self::PythonUnsupportedDocstring => "python-unsupported-docstring",
Self::PythonDocstringSourceAttribution => "python-docstring-source-attribution",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Severity {
Error,
Warning,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct DiagnosticPath(#[serde(deserialize_with = "deserialize_path")] String);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[error(
"diagnostic paths must be nonempty normalized relative paths with forward-slash separators"
)]
pub struct InvalidDiagnosticPath;
impl DiagnosticPath {
pub fn as_str(&self) -> &str {
&self.0
}
}
impl TryFrom<String> for DiagnosticPath {
type Error = InvalidDiagnosticPath;
fn try_from(value: String) -> Result<Self, Self::Error> {
if value.contains(['\\', '\0', ':'])
|| value
.split('/')
.any(|component| matches!(component, "" | "." | ".."))
{
return Err(InvalidDiagnosticPath);
}
Ok(Self(value))
}
}
impl TryFrom<&str> for DiagnosticPath {
type Error = InvalidDiagnosticPath;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Self::try_from(value.to_owned())
}
}
fn deserialize_path<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<String, D::Error> {
let path = DiagnosticPath::try_from(String::deserialize(deserializer)?)
.map_err(serde::de::Error::custom)?;
Ok(path.0)
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum DiagnosticSource {
Configuration {
path: DiagnosticPath,
},
Repository {
repository: String,
path: DiagnosticPath,
},
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum DiagnosticEntity {
Concept {
id: String,
},
Configuration,
ConfigurationField {
path: String,
},
Content {
id: String,
},
Document {
collection: String,
path: DiagnosticPath,
},
Item {
package: String,
id: String,
},
Package {
id: String,
},
Project,
Relationship {
index: usize,
},
Repository {
id: String,
},
Target {
package: String,
id: String,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Diagnostic {
pub code: DiagnosticCode,
pub severity: Severity,
pub message: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub related_entity: Option<DiagnosticEntity>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source: Option<DiagnosticSource>,
pub span: Option<SourceSpan>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub related_spans: Vec<SourceSpan>,
}
impl Diagnostic {
pub fn new(code: DiagnosticCode, severity: Severity, message: impl Into<String>) -> Self {
Self {
code,
severity,
message: message.into(),
related_entity: None,
source: None,
span: None,
related_spans: Vec::new(),
}
}
pub fn with_source(mut self, source: DiagnosticSource) -> Self {
self.source = Some(source);
self
}
pub fn with_entity(mut self, entity: DiagnosticEntity) -> Self {
self.related_entity = Some(entity);
self
}
}
impl Ord for Diagnostic {
fn cmp(&self, other: &Self) -> Ordering {
optional_last(&self.source, &other.source)
.then_with(|| optional_last(&self.span.map(span_key), &other.span.map(span_key)))
.then_with(|| self.code.as_str().cmp(other.code.as_str()))
.then_with(|| self.severity.cmp(&other.severity))
.then_with(|| optional_last(&self.related_entity, &other.related_entity))
.then_with(|| self.message.cmp(&other.message))
.then_with(|| {
self.related_spans
.iter()
.copied()
.map(span_key)
.cmp(other.related_spans.iter().copied().map(span_key))
})
}
}
impl PartialOrd for Diagnostic {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
fn span_key(span: SourceSpan) -> (usize, usize) {
(span.start, span.end)
}
fn optional_last<T: Ord>(left: &Option<T>, right: &Option<T>) -> Ordering {
match (left, right) {
(Some(left), Some(right)) => left.cmp(right),
(Some(_), None) => Ordering::Less,
(None, Some(_)) => Ordering::Greater,
(None, None) => Ordering::Equal,
}
}