4 ms·
I find that this kind of pattern can be useful if you have a default implementation for each visit_foo method. For example, suppose that you want to create a t
by ufo 6y ago
I find that this kind of pattern can be useful if you have a default implementation for each visit_foo method.
For example, suppose that you want to create a traversal that walks through the entire Ast and does something special on just the Name nodes. And another traversal that does something special on just the integer literal nodes. One way to do this is to create a default traversal that walks through the entire tree without doing anything and then create a "subclass" that overrides just the visit_name and another that overrides just the visit_expr method.
One place that I've seen this in the wild is the Ocaml compiler:
* https://github.com/ocaml/ocaml/blob/trunk/parsing/ast_iterator.mli https://github.com/ocaml/ocaml/blob/trunk/parsing/ast_iterat...
* https://github.com/ocaml/ocaml/blob/trunk/parsing/ast_mapper.mli https://github.com/ocaml/ocaml/blob/trunk/parsing/ast_mapper...
- qppo 6y agoOr create an iterator and use Iterator::filter, which is probably a bit more idiomatic.
- ufo 6y agoIn many languages, creating a pull-based iterator for a tree-shaped data-structure can be tricky. It might require turning the recursion inside out to use an explicit stack... Do you know how well Rust can handle this? I'm not familiar with the details. In any case, while an iterator might help in the "ast_iterator" example, in the "ast_mapper" example I am not sure if there is a way around it.