Basically I am trying to implement visitors-coding paradigm, where Expr trait needs to be implemented by Binary struct. I want to use Expr as a trait object. Any entity wanting to interact with Expr will need to implement Visitors trait. The visitor trait should also be a trait object with generic function so that different functions inside the trait can support different types. But this makes Expr and Visitors not trait object safe. Is there a way to implement what I am trying to achieve?
use crate::token_type::Token;
pub trait Expr {
fn accept<T>(&self, visitor: &dyn Visitor) -> T;
}
pub trait Visitor {
fn visit_binary_expr<T>(&self, expr: Binary) -> T;
}
impl Expr for Binary {
fn accept<T>(self, visitor: &dyn Visitor) -> T {
visitor.visit_binary_expr(self)
}
}
pub struct Binary {
left: Box<dyn Expr>,
operator: Token,
right: Box<dyn Expr>,
}
impl Binary {
fn new(left: Box<dyn Expr>, operator: Token, right: Box<dyn Expr>) -> Self {
Self {
left,
operator,
right,
}
}
}
struct ASTPrinter {}
impl ASTPrinter {
fn print(&self, expr: Box<dyn Expr>) -> &str {
expr.accept(self)
}
}
impl Visitor for ASTPrinter {
fn visit_binary_expr(&self, expr: Binary) -> &str {
"binary"
}
}
First, reconsider if you really want trait objects and not enums. Enums are a better way to model a closed set of types, like expressions.
If you insist on using trait objects, reconsider if your visitor really needs to be able to return something.
()-returning visitors are very simple to implement:Now, if you really need trait objects, and you really need to return values, then you need some boilerplate.
The idea is to have a result-type-erased visitor, that wraps a generic visitor but always returns
(), and keep the inner visitor's result in a field. Then, we have anaccept_impl()that takes&mut dyn Visitor<Result = ()>(that is, a visitor that returns()), and a wrapperaccept()that usesaccept_impl()andErasedVisitorto take any visitor and return its result:Then using this is like: