use core::any::Any;
pub use any_hint::AnyHint;
pub use any_visit::AnyVisit;
pub use id::ProtocolId;
use crate::{Visitor, WalkerHints, WalkStatus};
/// A protocol between a walker and visitor.
///
/// On the walker side this takes the form of hints a visitor can give.
/// On the visitor side this takes the form of visits a walker can inject values into.
///
/// When a visitor hints a walker should use a particular protocol, its expected
/// that the walker visits using that protocol.
///
/// A protocol never needs to be a value, so it's recommended to use an uninhabited type
/// like an empty enum to represent them.
pub trait Protocol: Any {
/// Arbitrary hint metadata for the protocol.
///
/// This allows a visitor to give extra information to a walker when hinting to
/// use the protocol.
type Hint<'ctx>;
/// Data known about the protocol before hinting.
///
/// This allows a walker to give extra information to a visitor to make a
/// better decision when selecting a hint.
type Known<'ctx>;
/// The visit data the walker provides to the visitor.
///
/// This may be actual data or another walker for a part of the bigger value.
/// The '`walking` lifetime is only alive while the walker is walking.
/// As such, a visitor cannot borrow from a `'walking` lifetime containing type
/// for it's output.
type Accessor<'walking, 'ctx: 'walking>;
}
#[derive(Copy, Clone)]
pub struct ProtocolDescription {
id: fn() -> ProtocolId,
name: fn() -> &'static str,
}
impl ProtocolDescription {
pub const fn of<P: Protocol>() -> Self {
Self {
id: || ProtocolId::of::<P>(),
name: || core::any::type_name::<P>(),
}
}
pub fn id(&self) -> ProtocolId {
(self.id)()
}
pub fn name(&self) -> &'static str {
(self.name)()
}
}
impl core::fmt::Display for ProtocolDescription {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}", self.name())
}
}
impl core::fmt::Debug for ProtocolDescription {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("ProtocolDescription")
.field("id", &self.id())
.field("name", &self.name())
.finish()
}
}
pub type HintOps<'walking, 'ctx, P> =
&'walking mut dyn Hint<'ctx, P>;
pub type VisitOps<'walking, 'ctx, P> =
&'walking mut dyn Visit<'ctx, P>;
/// Protocol specific hint for a walker.
pub trait Hint<'ctx, P: Protocol> {
/// Hint that protocol `P` should be used.
///
/// After hinting a protocol, a walker should invoke only the same protocol on the visitor.
/// This is not forced though.
fn hint(
&mut self,
visitor: &mut dyn Visitor<'ctx>,
hint: P::Hint<'ctx>,
) -> WalkStatus;
/// Any information the walker has for the protocol.
///
/// This information should be easy to get inside the walker, and should
/// only be used when making a decision of what protocol to hint as a visitor.
/// This can be helpful for doing things like preallocating space in the visitor.
///
/// Most protocols will allow returning a value representing no knowledge is known by the
/// walker.
fn known(
&mut self,
hint: &P::Hint<'ctx>,
) -> P::Known<'ctx>;
}
/// Protocol specific visit for a visitor.
pub trait Visit<'ctx, P: Protocol> {
/// Visit a value from the walker.
fn visit<'walking>(
&'walking mut self,
accessor: P::Accessor<'walking, 'ctx>,
);
}
pub trait ErrorWrongProtocol {
fn error_wrong_protocol<Expected: Protocol>(&mut self, got: ProtocolDescription);
}
pub trait ErrorMissingProtocol {
fn error_missing_protocol<P: Protocol>(&mut self);
}
pub fn try_lookup_hint<
'a,
'ctx,
P: Protocol,
E: ErrorWrongProtocol,
H: ?Sized + WalkerHints<'ctx>,
>(
hints: &'a mut H,
error_report: &mut E,
) -> Option<HintOps<'a, 'ctx, P>> {
match hints.protocol(ProtocolId::of::<P>()) {
Some(protocol) => match protocol.downcast::<P>() {
Ok(hint) => Some(hint),
Err(hint) => {
error_report.error_wrong_protocol::<P>(hint.description());
None
}
},
None => None,
}
}
pub fn lookup_hint<
'a,
'ctx,
P: Protocol,
E: ErrorWrongProtocol + ErrorMissingProtocol,
H: ?Sized + WalkerHints<'ctx>,
>(
hints: &'a mut H,
error_report: &mut E,
) -> Option<HintOps<'a, 'ctx, P>> {
match hints.protocol(ProtocolId::of::<P>()) {
Some(protocol) => match protocol.downcast::<P>() {
Ok(hint) => Some(hint),
Err(hint) => {
error_report.error_wrong_protocol::<P>(hint.description());
None
}
},
None => {
error_report.error_missing_protocol::<P>();
None
},
}
}
pub fn try_lookup_visit<
'a,
'ctx,
P: Protocol,
E: ErrorWrongProtocol,
V: ?Sized + Visitor<'ctx>,
>(
visitor: &'a mut V,
error_report: &mut E,
) -> Option<VisitOps<'a, 'ctx, P>> {
match visitor.protocol(ProtocolId::of::<P>()) {
Some(protocol) => match protocol.downcast::<P>() {
Ok(visit) => Some(visit),
Err(visit) => {
error_report.error_wrong_protocol::<P>(visit.description());
None
}
},
None => None,
}
}
pub fn lookup_visit<
'a,
'ctx,
P: Protocol,
E: ErrorWrongProtocol + ErrorMissingProtocol,
V: ?Sized + Visitor<'ctx>,
>(
visitor: &'a mut V,
error_report: &mut E,
) -> Option<VisitOps<'a, 'ctx, P>> {
match visitor.protocol(ProtocolId::of::<P>()) {
Some(protocol) => match protocol.downcast::<P>() {
Ok(visit) => Some(visit),
Err(visit) => {
error_report.error_wrong_protocol::<P>(visit.description());
None
}
},
None => {
error_report.error_missing_protocol::<P>();
None
},
}
}
mod id {
use super::Protocol;
use core::any::TypeId;
/// ID of a protocol.
///
/// This can be used to query if a walker or visitor supports a protocol.
#[derive(PartialEq, Eq, Hash, Ord, PartialOrd, Debug, Copy, Clone)]
pub struct ProtocolId(TypeId);
impl ProtocolId {
/// Get the ID of a protocol.
///
/// The ID is unique per protocol.
pub fn of<P: Protocol>() -> Self {
Self(TypeId::of::<P>())
}
}
}
mod any_hint {
use core::{any::Any, marker::PhantomData, mem::MaybeUninit};
use crate::Hint;
use super::{Protocol, ProtocolDescription, ProtocolId};
/// Form of `Hint` without `P`.
trait ErasedHint<'ctx>: Any {}
/// Get the size of pointers to trait objects for this target.
const DYN_PTR_SIZE: usize =
core::mem::size_of::<&mut dyn ErasedHint<'static>>();
/// Type erased form of `&'walking mut dyn Hint<'value, P, Err>` where `P` is erased.
pub struct AnyHint<'walking, 'ctx> {
/// ID of `P`.
id: ProtocolDescription,
/// This field stores a `&'walking mut dyn Hint<'value, P, Err>`.
fat_ptr: MaybeUninit<[u8; DYN_PTR_SIZE]>,
/// Mimick what we actually store with a trait without `P`.
_marker: PhantomData<&'walking mut dyn ErasedHint<'ctx>>,
}
impl<'walking, 'ctx>
AnyHint<'walking, 'ctx>
{
/// Erase the `P` in a hint.
///
/// This allows returning a hint from a object safe method.
pub fn new<P: Protocol>(
visit: &'walking mut dyn Hint<'ctx, P>,
) -> Self {
Self {
id: ProtocolDescription::of::<P>(),
// SAFETY: A maybe uninit array of bytes can hold any pointer.
// Additionally, transmute makes sure the size is correct.
fat_ptr: unsafe { core::mem::transmute(visit) },
_marker: PhantomData,
}
}
/// Try to downcast the hint for the given protocol.
///
/// If the hint is of the wrong type then `None` is returned.
pub fn downcast<P: Protocol>(
self,
) -> Result<&'walking mut dyn Hint<'ctx, P>, Self>
{
if self.id.id() == ProtocolId::of::<P>() {
// SAFETY: Only `new` can make a value of this type, and it stores the ID of `P`.
// If the IDs are equal then we can act like any and downcast back to the real
// type.
//
// An important note is this method takes ownership. Which allows it to return
// the borrow with the `'walking` lifetime instead of a sub-borrow.
Ok(unsafe { core::mem::transmute(self.fat_ptr) })
} else {
Err(self)
}
}
pub fn description(&self) -> ProtocolDescription {
self.id
}
}
}
mod any_visit {
use core::{any::Any, marker::PhantomData, mem::MaybeUninit};
use crate::Visit;
use super::{Protocol, ProtocolDescription, ProtocolId};
/// Form of `Visit` without `P`.
trait ErasedVisit<'ctx>: Any {}
/// Get the size of pointers to trait objects for this target.
const DYN_PTR_SIZE: usize =
core::mem::size_of::<&mut dyn ErasedVisit<'static>>();
/// Type erased form of `&'walking mut dyn Visit<'value, P, Err>` where `P` is erased.
pub struct AnyVisit<'walking, 'ctx> {
/// ID of `P`.
id: ProtocolDescription,
/// This field stores a `&'walking mut dyn Visit<'value, P, Err>`.
fat_ptr: MaybeUninit<[u8; DYN_PTR_SIZE]>,
/// Mimick what we actually store with a trait without `P`.
_marker: PhantomData<&'walking mut dyn ErasedVisit<'ctx>>,
}
impl<'walking, 'ctx>
AnyVisit<'walking, 'ctx>
{
/// Erase the `P` in a Visit.
///
/// This allows returning a Visit from a object safe method.
pub fn new<P: Protocol>(
visit: &'walking mut dyn Visit<'ctx, P>,
) -> Self {
Self {
id: ProtocolDescription::of::<P>(),
// SAFETY: A maybe uninit array of bytes can hold any pointer.
// Additionally, transmute makes sure the size is correct.
fat_ptr: unsafe { core::mem::transmute(visit) },
_marker: PhantomData,
}
}
/// Try to downcast the Visit for the given protocol.
///
/// If the Visit is of the wrong type then `None` is returned.
pub fn downcast<P: Protocol>(
self,
) -> Result<&'walking mut dyn Visit<'ctx, P>, Self>
{
if self.id.id() == ProtocolId::of::<P>() {
// SAFETY: Only `new` can make a value of this type, and it stores the ID of `P`.
// If the IDs are equal then we can act like any and downcast back to the real
// type.
//
// An important note is this method takes ownership. Which allows it to return
// the borrow with the `'walking` lifetime instead of a sub-borrow.
Ok(unsafe { core::mem::transmute(self.fat_ptr) })
} else {
Err(self)
}
}
pub fn description(&self) -> ProtocolDescription {
self.id
}
}
}
/// The following shows a safe form of the generic types in this module.
/// This shows how the lifetimes are correct.
#[cfg(test)]
#[allow(unused)]
mod generic_example {
use crate::Hint;
use super::{Protocol, ProtocolId};
pub struct Generic<'walking, 'ctx, P> {
id: ProtocolId,
fat_ptr: &'walking mut dyn Hint<'ctx, P>,
}
impl<'walking, 'ctx, P: Protocol>
Generic<'walking, 'ctx, P>
{
pub fn new(
visit: &'walking mut dyn Hint<'ctx, P>,
) -> Self {
Self {
id: ProtocolId::of::<P>(),
fat_ptr: visit,
}
}
pub fn downcast(
self,
) -> Result<&'walking mut dyn Hint<'ctx, P>, Self>
{
if self.id == ProtocolId::of::<P>() {
// Notice how this is valid.
Ok(self.fat_ptr)
} else {
Err(self)
}
}
}
}