Description
I explored the various ASTs on astexplorer.net and saw many possibilities. It would be fantastic to use pattern matching when dealing with trees parsed by parser libraries
But in my understanding, that requires converting JS objects to a record and is converted to a ReScript internal representation at runtime.
this feels unnecessary overhead when writing some bindings for a parser library. Because each item in the tree is already a tagged object.
Imagine a function like this:
@deriving(tagged)
type rec node =
| _Text({
@tag("#text") nodeName: string,
value: string,
})
| H1({
@tag("h1") nodeName: string,
childNodes: array<node>,
})
@val external nodes: nodes = "nodes"
let rec toText = nodes =>
nodes->Belt.Array.reduce((text, node) => text ++ " " ++ switch node {
| _Text({ value }) => value
| H1({ childNodes }) => toText(childNodes)
}, "")
nodes->toText // works without additional parsing
And its output, instead of TAG
, we can match via a tag we specify.
var match = node;
var tmp;
switch(match.nodeName) {
case '#text':
// ...
I think this can be a more ergonomic approach when writing bindings for parsers.
Currently, I have to rely on a 3rd party ppx like decco for this kind of work. Or please let me know if there is a better way I am not aware of