apollo-rs
apollo-rs copied to clipboard
Sketch of a visitor pattern
This visitor pattern is designed for doing normalizations on executable documents, so it assumes you will mutate the tree as it is walked. (Perhaps a better design would be to make each visitor return an object of the type it is visiting (which could be the same object it received), constructing a new tree (possibly sharing most of its data) immutably.)
This highlights some places where it would be helpful if the AST contained more explicit types where it currently only has variants, type aliases, or vecs. By having more little structs in the type system, it's easier to write a visitor like this that can easily target (say) every Name node. This includes:
- It would be helpful if all enums (which actually contain data, so not OperationType) had a specific type for each variant, so that visitors can choose to visit that variant specifically. Definition and Selection work this way already; Type and Value do not. This is especially helpful for Value, as it would be nice to be able to write visitors that visit just string values or int values or whatever without needing to match against the Value.
- Most uses of NodeStr in the AST are names or descriptions. It would be helpful if there were (non-alias) Name and Description types that could implement Walkable like the other AST types, and then you could implement
visit_name
, etc. (Sure, we could just callvisit_name
directly from each Walkable implementation for a type containing a name, but keeping the strict pattern of "eachwalk
callsvisit_*
exactly once and then callswalk
on its children" seems nice.) - It would be nice if some more of the Vec types were a struct like Directives, though I suppose implementing Walkable on
Vec<Selection>
isn't that much more awkward than implementing it onSelectionSet
. I'm thinkingSelectionSet
andArguments
specifically.
It's possible I'm missing something and the status quo is pretty reasonable though.
It would be nice if apollo-compiler had some sort of built-in visitor API; maybe this one, maybe a more immutable one, maybe something else. Whether or not apollo-compiler adds such an API, this PR hopefully at least points out some potential improvements in the AST data types.