Assuming I have a program like so:
let words = ["foo", "bar", "baz", "qux"]
for (var i = 0; i < words.length; i++) {
console.log(words[i])
}
I want to filter the AST and only keep the literals. How can I traverse the AST to keep only "foo", "bar", etc?
literals :: JSAST -> [String]
literals (JSAstProgram statements) = undefined
literals _ = []
The undefined line should filter the [JSStatement], and then look for possible expressions.
If an expression is found, check if there's a literal.
Lastly, map the list from a JSStatement -> String.
Looking for the possible expressions is the problem for me right now. I could pattern match:
f :: JSStatement -> a
f (JSLet _ expression _) = undefined
f (JSConstant _ expression _) = undefined
f (JsDoWhile _ _ _ _ expression _ _) = undefined
... etc
And then same thing for looking for the literal:
g :: JSExpression -> a
g (JSLiteral _ literal) = undefined
g (JSStringLiteral _ literal) = undefined
g (JSArrayLiteral _ literal _) = undefined
... etc
However, this is very verbose and I feel like there's something better out there. How do I traverse through the AST and filter out only the literals in a clean and concise manner?