use alloc::string::{String, ToString};
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::any::Any;
use core::fmt;
use core::marker::PhantomData;
use crate::engine::ParseResult;
use crate::error::Diagnostics;
use crate::node::NodeTree;
use crate::state::Lang;
use super::super::engine::{DeserializeContext, ObjectSerdeDriver, SerdeSession, SerializeContext};
use super::super::error::{DeserializeError, SerializeError};
use super::super::object::{
DeserializableObject, DeserializableValue, SerializableLang, SerializableObject,
SerializableValue,
};
use super::super::value::{SerialEntry, SerialValue};
use super::super::wire::parse_result::{WireDiagnostics, WireParseResult};
use super::super::wire::{FromSerialValue, ToSerialValue};
use super::standard::StandardTables;
use super::tree::tree_of_object;
use super::{PARSE_RESULTS_TABLE, PARSE_RESULT_IDENTIFIER, TREES_TABLE};
crate::serial_index! {
pub struct ParseResultIndex;
}
pub struct ParseResultSerdeDriver<L: Lang> {
lang: PhantomData<fn() -> L>,
}
impl<L: Lang> ParseResultSerdeDriver<L> {
pub fn new() -> ParseResultSerdeDriver<L> {
ParseResultSerdeDriver { lang: PhantomData }
}
}
impl<L: Lang> Default for ParseResultSerdeDriver<L> {
fn default() -> Self {
ParseResultSerdeDriver::new()
}
}
impl<L: Lang> fmt::Debug for ParseResultSerdeDriver<L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ParseResultSerdeDriver").finish()
}
}
impl<L: SerializableLang> ObjectSerdeDriver<L> for ParseResultSerdeDriver<L> {
type Object = ParseResult<L>;
type Index = ParseResultIndex;
fn table_name(&self) -> &'static str {
PARSE_RESULTS_TABLE
}
fn homogeneous_identifier(&self) -> Option<&'static str> {
Some(PARSE_RESULT_IDENTIFIER)
}
fn serialize_object(
&self,
result: &Arc<ParseResult<L>>,
cx: &mut SerializeContext<'_, L>,
) -> Result<SerialEntry, SerializeError> {
result.serialize_object(cx)
}
fn deserialize_object(
&self,
entry: &SerialEntry,
cx: &mut DeserializeContext<'_, L>,
) -> Result<Arc<ParseResult<L>>, DeserializeError> {
ParseResult::<L>::deserialize_object(&entry.data, cx).map(Arc::new)
}
}
fn missing_standard_table_name<L: SerializableLang>(session: &SerdeSession<L>) -> String {
session.missing_standard_table().unwrap_or(TREES_TABLE).to_string()
}
impl<L: Lang> SerializableObject<L> for ParseResult<L> {
fn serialize_object(&self, cx: &mut SerializeContext<'_, L>) -> Result<SerialEntry, SerializeError>
where
L: SerializableLang,
{
let Some(StandardTables { trees, diagnostics, .. }) = cx.standard_tables() else {
return Err(SerializeError::UnknownTableName {
name: missing_standard_table_name(cx.session_mut()),
});
};
let tree_object: Arc<dyn Any + Send + Sync> = Arc::new(self.tree.clone());
let tree = cx.intern(trees, &tree_object)?;
let items = self
.diagnostics
.iter()
.map(|diagnostic| cx.intern(diagnostics, &Arc::new(diagnostic.clone())))
.collect::<Result<Vec<_>, _>>()?;
let wire = WireParseResult {
tree,
diagnostics: WireDiagnostics {
items,
limit: self.diagnostics.limit(),
suppressed: self.diagnostics.suppressed(),
error_count: self.diagnostics.error_count(),
},
session_ext: self.session_ext.serialize_value(cx)?,
};
Ok(SerialEntry { identifier: PARSE_RESULT_IDENTIFIER.into(), data: wire.to_serial_value()? })
}
}
impl<L: SerializableLang> DeserializableObject<L> for ParseResult<L> {
type Output = ParseResult<L>;
fn deserialize_object(value: &SerialValue, cx: &mut DeserializeContext<'_, L>) -> Result<ParseResult<L>, DeserializeError> {
let wire = WireParseResult::from_serial_value(value)?;
let Some(StandardTables { trees, diagnostics, .. }) = cx.standard_tables() else {
return Err(DeserializeError::UnknownTableName {
name: missing_standard_table_name(cx.session_mut()),
});
};
let tree_object = cx.object(trees, wire.tree)?;
let tree: NodeTree<L> = tree_of_object(cx.session_mut(), tree_object)?;
let items = wire
.diagnostics
.items
.iter()
.map(|&position| cx.object(diagnostics, position).map(|diagnostic| (*diagnostic).clone()))
.collect::<Result<Vec<_>, _>>()?;
let session_ext = <L::SessionExt as DeserializableValue<L>>::deserialize_value(&wire.session_ext, cx)?;
let WireDiagnostics { limit, suppressed, error_count, .. } = wire.diagnostics;
let diagnostics = Diagnostics::from_parts(items, limit, suppressed, error_count)
.map_err(DeserializeError::InconsistentDiagnosticCounts)?;
Ok(ParseResult { tree, diagnostics, session_ext })
}
}
pub trait ParseResultSerialization<L: SerializableLang> {
fn serialize_parse_result(&mut self, result: &Arc<ParseResult<L>>) -> Result<ParseResultIndex, SerializeError>;
fn parse_result(&mut self, position: ParseResultIndex) -> Result<Arc<ParseResult<L>>, DeserializeError>;
}
impl<L: SerializableLang> ParseResultSerialization<L> for SerdeSession<L> {
fn serialize_parse_result(&mut self, result: &Arc<ParseResult<L>>) -> Result<ParseResultIndex, SerializeError> {
let handle = self
.table_handle::<ParseResultSerdeDriver<L>>(PARSE_RESULTS_TABLE)
.ok_or_else(|| SerializeError::UnknownTableName { name: PARSE_RESULTS_TABLE.to_string() })?;
self.intern(handle, result)
}
fn parse_result(&mut self, position: ParseResultIndex) -> Result<Arc<ParseResult<L>>, DeserializeError> {
let handle = self
.table_handle::<ParseResultSerdeDriver<L>>(PARSE_RESULTS_TABLE)
.ok_or_else(|| DeserializeError::UnknownTableName { name: PARSE_RESULTS_TABLE.to_string() })?;
self.object(handle, position)
}
}