use alloc::borrow::Cow;
use alloc::boxed::Box;
use alloc::string::String;
use alloc::sync::Arc;
use core::fmt;
use crate::error::InconsistentDiagnosticCounts;
use crate::scopes::DefinitionKey;
use super::value::TableId;
type SharedCause = Arc<dyn core::error::Error + Send + Sync + 'static>;
struct OriginLabel<'a>(&'a Option<String>);
impl fmt::Display for OriginLabel<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.0 {
Some(label) => write!(f, "`{label}`"),
None => f.write_str("(no origin)"),
}
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum SerializeError {
Unsupported,
ArgumentSpecOutOfBand {
index: usize,
count: usize,
},
Failed {
detail: String,
cause: Option<SharedCause>,
},
Value(SerialValueError),
UnknownTable {
table: TableId,
},
UnknownTableName {
name: String,
},
TableFull {
table: &'static str,
},
IndexOutOfRange {
table: &'static str,
index: u32,
len: u32,
},
ReferenceCycle {
table: &'static str,
referrer: &'static str,
},
DescentLimitExceeded {
detail: String,
},
UnexpectedIdentifier {
table: &'static str,
expected: &'static str,
found: String,
},
MissingProvenance {
spec: &'static str,
},
ProviderDropped {
callable_type: String,
key: DefinitionKey,
},
InTable {
table: &'static str,
cause: Box<SerializeError>,
},
InNode {
node: u32,
callable: Option<String>,
cause: Box<SerializeError>,
},
}
impl SerializeError {
pub fn unsupported() -> SerializeError {
SerializeError::Unsupported
}
pub fn failed(detail: impl Into<String>) -> SerializeError {
SerializeError::Failed { detail: detail.into(), cause: None }
}
pub fn with_cause(self, cause: impl core::error::Error + Send + Sync + 'static) -> SerializeError {
match self {
SerializeError::Failed { detail, .. } => {
SerializeError::Failed { detail, cause: Some(Arc::new(cause)) }
}
other => other,
}
}
pub(crate) fn in_table(self, table: &'static str) -> SerializeError {
match self {
located @ SerializeError::InTable { .. } => located,
cause => SerializeError::InTable { table, cause: Box::new(cause) },
}
}
pub(crate) fn in_node(self, node: u32, callable: Option<String>) -> SerializeError {
match self {
located @ SerializeError::InNode { .. } => located,
cause => SerializeError::InNode { node, callable, cause: Box::new(cause) },
}
}
}
impl From<SerialValueError> for SerializeError {
fn from(error: SerialValueError) -> SerializeError {
SerializeError::Value(error)
}
}
impl fmt::Display for SerializeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
SerializeError::Unsupported => {
write!(f, "serialization is unsupported by this type")
}
SerializeError::ArgumentSpecOutOfBand { index, count } => write!(
f,
"argument #{} was parsed against an argument spec its callable spec does \
not declare at that index ({} declared); the callable spec must \
implement serialize_argument_spec to serialize it",
index.saturating_add(1),
count
),
SerializeError::Failed { detail, .. } => {
write!(f, "serialization failed: {detail}")
}
SerializeError::Value(error) => {
write!(f, "the value cannot be represented in the serialized form: {error}")
}
SerializeError::UnknownTable { table } => write!(
f,
"table #{} is not registered in this session (the handle comes from another \
session, or the table was registered with a different driver type)",
table.ordinal()
),
SerializeError::UnknownTableName { name } => write!(
f,
"no table named `{name}` is registered in this session with the expected \
driver type"
),
SerializeError::TableFull { table } => {
write!(f, "table `{table}` is full (u32::MAX entries)")
}
SerializeError::IndexOutOfRange { table, index, len } => write!(
f,
"position #{index} of table `{table}` does not exist (the table holds {len} entries)"
),
SerializeError::ReferenceCycle { table, referrer } => write!(
f,
"serialized references would form a cycle: an object of table `{table}` \
whose serialization is in progress was interned again while serializing \
an object of table `{referrer}`"
),
SerializeError::DescentLimitExceeded { detail } => {
write!(f, "serialization descent limit exceeded: {detail}")
}
SerializeError::UnexpectedIdentifier { table, expected, found } => write!(
f,
"the driver of table `{table}` produced an entry with identifier `{found}`, \
but every entry of that table must carry `{expected}`"
),
SerializeError::MissingProvenance { spec } => write!(
f,
"a `{spec}` carries no provenance stamp: it was built outside a shared \
package (see Package::new_shared) and its type has no self-contained \
serialized form, so it cannot be serialized"
),
SerializeError::ProviderDropped { callable_type, key } => write!(
f,
"the provider that defined the spec ({callable_type}, {key}) no longer \
exists, so the spec's identity cannot be serialized"
),
SerializeError::InTable { table, cause } => {
write!(f, "while serializing an object into table `{table}`: {cause}")
}
SerializeError::InNode { node, callable, cause } => match callable {
Some(callable) => {
write!(f, "while serializing node #{node} (callable `{callable}`) of the tree: {cause}")
}
None => write!(f, "while serializing node #{node} of the tree: {cause}"),
},
}
}
}
impl core::error::Error for SerializeError {
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
match self {
SerializeError::Failed { cause, .. } => {
cause.as_ref().map(|cause| &**cause as &(dyn core::error::Error + 'static))
}
SerializeError::Value(error) => Some(error),
SerializeError::InTable { cause, .. } | SerializeError::InNode { cause, .. } => Some(&**cause),
_ => None,
}
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum DeserializeError {
ArgumentIndexOutOfRange {
index: usize,
count: usize,
},
UnexpectedArgumentSpecPayload {
index: usize,
},
Failed {
detail: String,
cause: Option<SharedCause>,
},
Value(SerialValueError),
UnknownTable {
table: TableId,
},
IndexOutOfRange {
table: &'static str,
index: u32,
len: u32,
},
WrongTable {
expected: &'static str,
found: TableId,
},
ReferenceCycle {
table: &'static str,
index: u32,
referrer_table: &'static str,
referrer_index: u32,
},
DescentLimitExceeded {
detail: String,
},
UnknownIdentifier {
table: &'static str,
identifier: String,
},
UnsupportedVersion {
found: u32,
expected: u32,
},
ProfileMismatch {
expected: String,
found: Option<String>,
},
UnknownTableName {
name: String,
},
SpanOutOfBounds {
start: usize,
end: usize,
len: usize,
},
SpanNotOnCharBoundary {
start: usize,
end: usize,
},
FeatureAbsent {
feature: &'static str,
},
NoSourceTextSupplier {
origin: Option<String>,
},
SourceLengthMismatch {
origin: Option<String>,
expected: usize,
found: usize,
},
SourceDigestMismatch {
origin: Option<String>,
algorithm: String,
},
DuplicateSegmentTable {
name: String,
},
SegmentOutOfOrder {
table: &'static str,
expected: u32,
found: u32,
},
UnemittedEntries {
table: &'static str,
},
UnknownWriterTable {
table: TableId,
},
TableFull {
table: &'static str,
},
Internal {
detail: String,
},
MissingProvider {
name: String,
},
MissingDefinition {
provider: String,
callable_type: String,
key: DefinitionKey,
},
UnrepresentableDiagnosticValue {
kind: &'static str,
path: String,
},
InconsistentDiagnosticCounts(
InconsistentDiagnosticCounts,
),
InEntry {
table: &'static str,
index: u32,
identifier: Option<Cow<'static, str>>,
cause: Box<DeserializeError>,
},
InNode {
node: u32,
callable: Option<String>,
cause: Box<DeserializeError>,
},
}
impl DeserializeError {
pub fn failed(detail: impl Into<String>) -> DeserializeError {
DeserializeError::Failed { detail: detail.into(), cause: None }
}
pub fn with_cause(self, cause: impl core::error::Error + Send + Sync + 'static) -> DeserializeError {
match self {
DeserializeError::Failed { detail, .. } => {
DeserializeError::Failed { detail, cause: Some(Arc::new(cause)) }
}
other => other,
}
}
pub(crate) fn in_entry(
self,
table: &'static str,
index: u32,
identifier: Option<Cow<'static, str>>,
) -> DeserializeError {
match self {
located @ DeserializeError::InEntry { .. } => located,
cause => DeserializeError::InEntry { table, index, identifier, cause: Box::new(cause) },
}
}
pub(crate) fn in_node(self, node: u32, callable: Option<String>) -> DeserializeError {
match self {
located @ DeserializeError::InNode { .. } => located,
cause => DeserializeError::InNode { node, callable, cause: Box::new(cause) },
}
}
}
impl From<SerialValueError> for DeserializeError {
fn from(error: SerialValueError) -> DeserializeError {
DeserializeError::Value(error)
}
}
impl fmt::Display for DeserializeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
DeserializeError::ArgumentIndexOutOfRange { index, count } => write!(
f,
"serialized argument #{} refers to a declared argument spec by index, \
but the callable spec declares only {} argument specs",
index.saturating_add(1),
count
),
DeserializeError::UnexpectedArgumentSpecPayload { index } => write!(
f,
"serialized argument #{} carries a description of its argument spec, but \
the callable spec it is read against does not override \
deserialize_argument_spec to read one (the callable spec type that wrote \
the argument differs from the one reading it)",
index.saturating_add(1)
),
DeserializeError::Failed { detail, .. } => {
write!(f, "deserialization failed: {detail}")
}
DeserializeError::Value(error) => {
write!(f, "malformed serialized value: {error}")
}
DeserializeError::UnknownTable { table } => write!(
f,
"table #{} is not registered in this session (the handle comes from another \
session, or the table was registered with a different driver type)",
table.ordinal()
),
DeserializeError::IndexOutOfRange { table, index, len } => write!(
f,
"reference to entry #{index} of table `{table}`, which holds {len} entries"
),
DeserializeError::WrongTable { expected, found } => write!(
f,
"a position in table #{} was read through the handle of table `{expected}`",
found.ordinal()
),
DeserializeError::ReferenceCycle { table, index, referrer_table, referrer_index } => {
write!(
f,
"serialized references form a cycle: entry #{index} of table `{table}`, \
whose deserialization is in progress, was read again while \
deserializing entry #{referrer_index} of table `{referrer_table}`"
)
}
DeserializeError::DescentLimitExceeded { detail } => {
write!(f, "deserialization descent limit exceeded: {detail}")
}
DeserializeError::UnknownIdentifier { table, identifier } => write!(
f,
"no reader is registered for identifier `{identifier}` in table `{table}` \
(nothing was registered for it, or the resolvers of its namespace declined)"
),
DeserializeError::UnsupportedVersion { found, expected } => write!(
f,
"segment version {found} is not supported (this crate reads version {expected})"
),
DeserializeError::ProfileMismatch { expected, found } => match found {
Some(found) => write!(
f,
"the segment's profile `{found}` is not this session's profile `{expected}`"
),
None => write!(f, "the segment carries no profile; this session requires `{expected}`"),
},
DeserializeError::UnknownTableName { name } => write!(
f,
"no table named `{name}` is registered in this session with the expected \
driver type"
),
DeserializeError::SpanOutOfBounds { start, end, len } => write!(
f,
"serialized span {start}..{end} does not fit its source ({len} bytes)"
),
DeserializeError::SpanNotOnCharBoundary { start, end } => write!(
f,
"serialized span {start}..{end} does not fall on character boundaries of \
its source"
),
DeserializeError::FeatureAbsent { feature } => write!(
f,
"the serialized data uses the `{feature}` feature, which the reading \
language declares absent"
),
DeserializeError::NoSourceTextSupplier { origin } => write!(
f,
"source {} is serialized by reference (its text is not embedded), but no \
supplier of referenced source text is configured",
OriginLabel(origin)
),
DeserializeError::SourceLengthMismatch { origin, expected, found } => write!(
f,
"the text supplied for source {} is {found} bytes long, but the entry \
records {expected} bytes",
OriginLabel(origin)
),
DeserializeError::SourceDigestMismatch { origin, algorithm } => write!(
f,
"the text supplied for source {} does not match its recorded `{algorithm}` \
digest",
OriginLabel(origin)
),
DeserializeError::DuplicateSegmentTable { name } => write!(
f,
"the segment lists table `{name}` twice (or reuses its writer-side table id)"
),
DeserializeError::SegmentOutOfOrder { table, expected, found } => write!(
f,
"the segment's entries for table `{table}` start at position {found}, but the \
table holds {expected} entries (segments must be pushed in stream order)"
),
DeserializeError::UnemittedEntries { table } => write!(
f,
"table `{table}` has entries interned since the last emission; emit them with \
take_segment before absorbing a segment"
),
DeserializeError::UnknownWriterTable { table } => write!(
f,
"a reference names writer-side table #{}, which the segment's table \
directory does not list",
table.ordinal()
),
DeserializeError::TableFull { table } => write!(
f,
"absorbing the segment would give table `{table}` more than u32::MAX entries"
),
DeserializeError::Internal { detail } => {
write!(f, "internal error of the serialization session (a bug in this crate): {detail}")
}
DeserializeError::MissingProvider { name } => write!(
f,
"the reading environment holds no provider named `{name}` (neither a \
provider nor a recipe of that name in the session's KnownProviders)"
),
DeserializeError::MissingDefinition { provider, callable_type, key } => write!(
f,
"the provider `{provider}` of the reading environment has no definition \
under {callable_type} with {key}"
),
DeserializeError::UnrepresentableDiagnosticValue { kind, path } => {
write!(
f,
"the diagnostic's condition data holds a value of kind `{kind}` "
)?;
if path.is_empty() {
write!(f, "at its root")?;
} else {
write!(f, "at `{path}`")?;
}
write!(
f,
", which a DiagnosticValue cannot hold (only null, booleans, integers, \
strings, lists, and string-keyed maps)"
)
}
DeserializeError::InconsistentDiagnosticCounts(counts) => {
write!(f, "{counts}")
}
DeserializeError::InEntry { table, index, identifier, cause } => match identifier {
Some(identifier) => write!(
f,
"while deserializing entry #{index} (`{identifier}`) of table `{table}`: \
{cause}"
),
None => write!(f, "while deserializing entry #{index} of table `{table}`: {cause}"),
},
DeserializeError::InNode { node, callable, cause } => match callable {
Some(callable) => {
write!(f, "while rebuilding node #{node} (callable `{callable}`) of the tree: {cause}")
}
None => write!(f, "while rebuilding node #{node} of the tree: {cause}"),
},
}
}
}
impl core::error::Error for DeserializeError {
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
match self {
DeserializeError::Failed { cause, .. } => {
cause.as_ref().map(|cause| &**cause as &(dyn core::error::Error + 'static))
}
DeserializeError::Value(error) => Some(error),
DeserializeError::InconsistentDiagnosticCounts(error) => Some(error),
DeserializeError::InEntry { cause, .. } | DeserializeError::InNode { cause, .. } => Some(&**cause),
_ => None,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum RegistrationError {
DuplicateTableName {
name: &'static str,
},
TooManyTables,
UnknownTable {
table: TableId,
},
UnknownTableName {
name: String,
},
DuplicateIdentifier {
table: &'static str,
identifier: String,
},
EmptyHomogeneousIdentifier {
table: &'static str,
},
DuplicateAnnotationType {
table: &'static str,
},
}
impl fmt::Display for RegistrationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
RegistrationError::DuplicateTableName { name } => {
write!(f, "a table named `{name}` is already registered in this session")
}
RegistrationError::TooManyTables => {
write!(f, "the session already has u32::MAX tables")
}
RegistrationError::UnknownTable { table } => write!(
f,
"table #{} is not registered in this session (the handle comes from another \
session, or the table was registered with a different driver type)",
table.ordinal()
),
RegistrationError::UnknownTableName { name } => write!(
f,
"no table named `{name}` is registered in this session with the expected \
driver type"
),
RegistrationError::DuplicateIdentifier { table, identifier } => write!(
f,
"a reader is already registered for identifier `{identifier}` in table `{table}`"
),
RegistrationError::EmptyHomogeneousIdentifier { table } => write!(
f,
"the driver of table `{table}` declares the empty string as its homogeneous \
identifier (an identifier is a non-empty string; a heterogeneous table \
declares none)"
),
RegistrationError::DuplicateAnnotationType { table } => write!(
f,
"that annotation type is already registered in table `{table}` \
(a tree annotation type is registered once)"
),
}
}
}
impl core::error::Error for RegistrationError {}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum SerialValueError {
FloatRejected,
NonStringMapKey,
ReservedMapKey {
key: String,
},
IntegerOutOfRange {
value: String,
target: &'static str,
},
TypeMismatch {
expected: Cow<'static, str>,
found: &'static str,
},
MissingField {
name: &'static str,
},
UnknownField {
name: String,
expected: &'static [&'static str],
},
DuplicateField {
name: String,
},
UnknownVariant {
name: String,
expected: &'static [&'static str],
},
NestingTooDeep {
limit: usize,
},
Custom(String),
}
impl fmt::Display for SerialValueError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
SerialValueError::FloatRejected => {
write!(f, "floating-point numbers have no serialized value form")
}
SerialValueError::NonStringMapKey => {
write!(f, "map keys must be strings in the serialized value form")
}
SerialValueError::ReservedMapKey { key } => {
write!(f, "map key `{key}` begins with `$`, which is reserved for the serialized value form's own objects")
}
SerialValueError::IntegerOutOfRange { value, target } => {
write!(f, "integer {value} does not fit {target}")
}
SerialValueError::TypeMismatch { expected, found } => {
write!(f, "expected {expected}, found {found}")
}
SerialValueError::MissingField { name } => write!(f, "missing key `{name}`"),
SerialValueError::UnknownField { name, expected } => {
write!(f, "unknown key `{name}`; expected ")?;
write_name_list(f, expected)
}
SerialValueError::DuplicateField { name } => write!(f, "repeated key `{name}`"),
SerialValueError::UnknownVariant { name, expected } => {
write!(f, "unknown variant `{name}`; expected ")?;
write_name_list(f, expected)
}
SerialValueError::NestingTooDeep { limit } => {
write!(f, "the value nests deeper than {limit} levels of lists and maps")
}
SerialValueError::Custom(message) => f.write_str(message),
}
}
}
fn write_name_list(f: &mut fmt::Formatter<'_>, names: &[&str]) -> fmt::Result {
match names {
[] => write!(f, "none"),
[only] => write!(f, "`{only}`"),
_ => {
write!(f, "one of ")?;
for (i, name) in names.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "`{name}`")?;
}
Ok(())
}
}
}
impl core::error::Error for SerialValueError {}