use alloc::borrow::Cow;
use alloc::boxed::Box;
use alloc::string::String;
use alloc::sync::Arc;
use core::fmt;
use crate::engine::DescentLimit;
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, "source ‘{label}’"),
None => f.write_str("a source without origin label"),
}
}
}
#[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,
limit: DescentLimit,
},
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 not supported by the type of this object")
}
SerializeError::ArgumentSpecOutOfBand { index, count } => write!(
f,
"Unsupported out-of-band argument spec of argument #{} (the callable spec \
declares {} argument specs); override \
‘serialize_argument_spec’ in the callable spec",
index.saturating_add(1),
count
),
SerializeError::Failed { detail, .. } => {
write!(f, "Serialization failed: {detail}")
}
SerializeError::Value(error) => {
write!(f, "Failed to convert a value to the serialized value model: {error}")
}
SerializeError::UnknownTable { table } => write!(
f,
"Unknown table #{} in this session: the table handle comes from another \
session, or the table has a driver of another type",
table.ordinal()
),
SerializeError::UnknownTableName { name } => write!(
f,
"Missing table ‘{name}’: no table of this name with the expected \
driver type is registered in this session"
),
SerializeError::TableFull { table } => {
write!(f, "Table ‘{table}’ is full (u32::MAX entries)")
}
SerializeError::IndexOutOfRange { table, index, len } => write!(
f,
"Position #{index} is out of range for table ‘{table}’ ({len} entries)"
),
SerializeError::ReferenceCycle { table, referrer } => write!(
f,
"Reference cycle: an object of table ‘{table}’ refers back to \
itself (interned again by an object of table ‘{referrer}’)"
),
SerializeError::DescentLimitExceeded { detail, .. } => {
write!(f, "Objects nested too deeply for serialization: {detail}")
}
SerializeError::UnexpectedIdentifier { table, expected, found } => write!(
f,
"Misconfigured driver of table ‘{table}’: the driver produced an \
entry with identifier ‘{found}’ (expected ‘{expected}’)"
),
SerializeError::MissingProvenance { spec } => write!(
f,
"Missing provenance stamp on a spec of type ‘{spec}’"
),
SerializeError::ProviderDropped { callable_type, key } => write!(
f,
"Missing definition provider of the spec with {key} (callable \
type ‘{callable_type}’)"
),
SerializeError::InTable { table, cause } => {
write!(f, "Failed to serialize an object into table ‘{table}’: {cause}")
}
SerializeError::InNode { node, callable, cause } => match callable {
Some(callable) => write!(
f,
"Failed to serialize node #{node} (callable ‘{callable}’) of a \
tree: {cause}"
),
None => write!(f, "Failed to serialize node #{node} of a 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,
},
AnnotationTypeMismatch {
stored: Option<String>,
requested: &'static str,
requested_identifier: Option<String>,
},
ReferenceCycle {
table: &'static str,
index: u32,
referrer_table: &'static str,
referrer_index: u32,
},
DescentLimitExceeded {
detail: String,
limit: DescentLimit,
},
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,
"Missing argument spec for serialized argument #{}: the callable spec \
declares only {} argument specs",
index.saturating_add(1),
count
),
DeserializeError::UnexpectedArgumentSpecPayload { index } => write!(
f,
"Unexpected description of the argument spec of serialized argument #{}: \
the callable spec does not override ‘deserialize_argument_spec’",
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,
"Unknown table #{} in this session: the table handle comes from another \
session, or the table has a driver of another type",
table.ordinal()
),
DeserializeError::IndexOutOfRange { table, index, len } => write!(
f,
"Position #{index} is out of range for table ‘{table}’ ({len} entries)"
),
DeserializeError::WrongTable { expected, found } => write!(
f,
"Table mismatch: a position of table #{} was read through the handle of table \
‘{expected}’",
found.ordinal()
),
DeserializeError::AnnotationTypeMismatch { stored, requested, requested_identifier } => {
write!(f, "Invalid annotation type ‘{requested}’ (")?;
match requested_identifier {
Some(identifier) => write!(f, "identifier ‘{identifier}’")?,
None => f.write_str("unregistered")?,
}
match stored {
Some(identifier) => {
write!(f, ") for a tree with annotation identifier ‘{identifier}’")
}
None => f.write_str(") for a tree of an unregistered annotation type"),
}
}
DeserializeError::ReferenceCycle { table, index, referrer_table, referrer_index } => {
write!(
f,
"Reference cycle: entry #{index} of table ‘{table}’ refers back \
to itself (read again by entry #{referrer_index} of table \
‘{referrer_table}’)"
)
}
DeserializeError::DescentLimitExceeded { detail, .. } => {
write!(f, "Serialized entries nested too deeply: {detail}")
}
DeserializeError::UnknownIdentifier { table, identifier } => write!(
f,
"Missing reader for identifier ‘{identifier}’ in table \
‘{table}’"
),
DeserializeError::UnsupportedVersion { found, expected } => write!(
f,
"Unsupported segment version {found} (this version of techy reads version \
{expected})"
),
DeserializeError::ProfileMismatch { expected, found } => match found {
Some(found) => write!(
f,
"Segment profile ‘{found}’ does not match the session profile \
‘{expected}’"
),
None => write!(
f,
"Missing segment profile: the session requires profile \
‘{expected}’"
),
},
DeserializeError::UnknownTableName { name } => write!(
f,
"Missing table ‘{name}’: no table of this name with the expected \
driver type is registered in this session"
),
DeserializeError::SpanOutOfBounds { start, end, len } => {
if start > end {
write!(
f,
"Invalid serialized span {start}..{end}: the start may not exceed \
the end"
)
} else {
write!(f, "Invalid serialized span {start}..{end}: the source has {len} bytes")
}
}
DeserializeError::SpanNotOnCharBoundary { start, end } => write!(
f,
"Invalid serialized span {start}..{end}: the span must start and end on \
character boundaries of the source"
),
DeserializeError::FeatureAbsent { feature } => write!(
f,
"Unsupported parsing feature ‘{feature}’ in serialized data (the \
reading language declares this feature absent)"
),
DeserializeError::NoSourceTextSupplier { origin } => write!(
f,
"Missing supplier of referenced source text for {}",
OriginLabel(origin)
),
DeserializeError::SourceLengthMismatch { origin, expected, found } => write!(
f,
"Wrong length of the text supplied for {}: {found} bytes, expected \
{expected} bytes",
OriginLabel(origin)
),
DeserializeError::SourceDigestMismatch { origin, algorithm } => write!(
f,
"Text supplied for {} does not match the recorded \
‘{algorithm}’ digest",
OriginLabel(origin)
),
DeserializeError::DuplicateSegmentTable { name } => write!(
f,
"Duplicate table ‘{name}’ in segment (repeated name or writer-side \
table identifier)"
),
DeserializeError::SegmentOutOfOrder { table, expected, found } => write!(
f,
"Segment out of order: its entries for table ‘{table}’ start at \
position {found}; the table has {expected} entries"
),
DeserializeError::UnemittedEntries { table } => write!(
f,
"Unemitted entries in table ‘{table}’: call \
‘take_segment’ before absorbing a segment"
),
DeserializeError::UnknownWriterTable { table } => write!(
f,
"Unknown writer-side table #{} in a reference: the table directory of the \
segment does not list it",
table.ordinal()
),
DeserializeError::TableFull { table } => write!(
f,
"Segment exceeds the capacity of table ‘{table}’ \
(u32::MAX entries)"
),
DeserializeError::Internal { detail } => {
write!(f, "Internal error in the serialization session (a bug in techy): {detail}")
}
DeserializeError::MissingProvider { name } => write!(
f,
"Missing provider ‘{name}’ in the ‘KnownProviders’ \
of the session"
),
DeserializeError::MissingDefinition { provider, callable_type, key } => write!(
f,
"Missing definition with {key} (callable type ‘{callable_type}’) \
in provider ‘{provider}’"
),
DeserializeError::UnrepresentableDiagnosticValue { kind, path } => {
write!(
f,
"Invalid value of kind ‘{kind}’ in the data of a serialized \
diagnostic, "
)?;
if path.is_empty() {
write!(f, "at the root")?;
} else {
write!(f, "at ‘{path}’")?;
}
write!(
f,
" (diagnostic values can contain 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,
"Failed to deserialize entry #{index} (identifier \
‘{identifier}’) of table ‘{table}’: {cause}"
),
None => write!(
f,
"Failed to deserialize entry #{index} of table ‘{table}’: \
{cause}"
),
},
DeserializeError::InNode { node, callable, cause } => match callable {
Some(callable) => write!(
f,
"Failed to rebuild node #{node} (callable ‘{callable}’) of a \
tree: {cause}"
),
None => write!(f, "Failed to rebuild node #{node} of a 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, "Duplicate table name ‘{name}’ in this session")
}
RegistrationError::TooManyTables => {
write!(f, "Too many tables: the session already has u32::MAX tables")
}
RegistrationError::UnknownTable { table } => write!(
f,
"Unknown table #{} in this session: the table handle comes from another \
session, or the table has a driver of another type",
table.ordinal()
),
RegistrationError::UnknownTableName { name } => write!(
f,
"Missing table ‘{name}’: no table of this name with the expected \
driver type is registered in this session"
),
RegistrationError::DuplicateIdentifier { table, identifier } => write!(
f,
"Duplicate reader for identifier ‘{identifier}’ in table \
‘{table}’"
),
RegistrationError::EmptyHomogeneousIdentifier { table } => write!(
f,
"Misconfigured driver of table ‘{table}’: the homogeneous \
identifier may not be empty; return ‘None’ for a table with \
objects of several kinds"
),
RegistrationError::DuplicateAnnotationType { table } => write!(
f,
"Duplicate registration of a tree annotation type in table \
‘{table}’"
),
}
}
}
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, "Unsupported floating-point number (serialized values have no floating-point type)")
}
SerialValueError::NonStringMapKey => {
write!(f, "Invalid map key: map keys must be strings")
}
SerialValueError::ReservedMapKey { key } => {
write!(f, "Invalid map key ‘{key}’: map keys may not begin with ‘$’")
}
SerialValueError::IntegerOutOfRange { value, target } => {
write!(f, "Integer {value} is out of range for ‘{target}’")
}
SerialValueError::TypeMismatch { expected, found } => {
write!(f, "Invalid value of kind ‘{found}’: expected {expected}")
}
SerialValueError::MissingField { name } => write!(f, "Missing key ‘{name}’"),
SerialValueError::UnknownField { name, expected } => {
write!(f, "Unknown key ‘{name}’")?;
if expected.is_empty() {
write!(f, " (expected no keys)")
} else {
write!(f, " (expected ")?;
write_name_list(f, expected)?;
write!(f, ")")
}
}
SerialValueError::DuplicateField { name } => write!(f, "Duplicate key ‘{name}’"),
SerialValueError::UnknownVariant { name, expected } => {
write!(f, "Unknown variant ‘{name}’")?;
if expected.is_empty() {
write!(f, " (expected no variants)")
} else {
write!(f, " (expected ")?;
write_name_list(f, expected)?;
write!(f, ")")
}
}
SerialValueError::NestingTooDeep { limit } => {
write!(f, "Value nested too deeply (more 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 {
[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 {}