Skip to content

Add derive macro for template::context::Context #50

@tyilo

Description

@tyilo

I would imagine that it would work like this:

#[derive(Context)]
struct MyContext {
    string: String,
    opt_string: Option<String>,
    list: Vec<String>,
    assoc: HashMap<String, String>,
}

Generated code:

impl Context for MyContext {
    fn visit<V: Visitor>(&self, visitor: V) -> V::Result {
        match visitor.var_name().as_str() {
            "string" => self.string.visit_with(visitor),
            "opt_string" => self.opt_string.visit_with(visitor),
            "list" => self.list.visit_with(visitor),
            "assoc" => self.assoc.visit_with(visitor),
            _ => visitor.visit_undefined(),
        }
    }
}

New VisitWith trait required for this:

pub trait VisitWith {
    fn visit_with<V: Visitor>(&self, visitor: V) -> V::Result;
}

impl<T: VisitWith> VisitWith for Option<T> {
    fn visit_with<V: Visitor>(&self, visitor: V) -> V::Result {
        match self {
            Some(v) => v.visit_with(visitor),
            None => visitor.visit_undefined(),
        }
    }
}

impl VisitWith for String {
    fn visit_with<V: Visitor>(&self, visitor: V) -> V::Result {
        visitor.visit_string(self)
    }
}

impl VisitWith for str {
    fn visit_with<V: Visitor>(&self, visitor: V) -> V::Result {
        visitor.visit_string(self)
    }
}

impl<T: Display> VisitWith for [T] { // Also for Vec<T>, [T; N]
    fn visit_with<V: Visitor>(&self, visitor: V) -> V::Result {
        visitor.visit_list().visit_items_and_finish(self)
    }
}

impl<K: Display, T: Display> VisitWith for HashMap<K, T> { // Also for BTreeMap
    fn visit_with<V: Visitor>(&self, visitor: V) -> V::Result {
        visitor.visit_assoc().visit_entries_and_finish(self)
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    designNeeds careful design decisionenhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions