Non-trivial uses of Ast_pattern module from ppxlib

ppx
ppxlib

#1

I’m wondering if the convenience modules for writing PPX extensions discussed by Rudi Grinberg in this blog post can easily accommodate slightly more complex cases, or if one has to go back to destructuring the parse tree “by hand” for all but the simplest examples.

For instance, suppose I had an extension “%foo” that instead of processing expressions consisting of just a string (ex: [%foo "hello"]), it would instead process expressions where a variant constructor has one string parameter(ex: [%foo Alpha "hello"]).

The just-a-string pattern can easily be captured by Ast_pattern.(single_expr_payload (estring __)), but I could not find an obvious way of capturing the variant-construct-with-string example. Note that I expect to capture two strings: “Alpha” (the string representation of the variant constructor Alpha), and the string constant “hello”.

Anyway, is this functionality buried somewhere in the huge Ast_pattern module, or must I indeed destructure the AST the old fashioned way?


#2

How about Ast_pattern.(single_expr_payload (pexp_construct (lident __) (some (estring __))))?

I found this by putting Alpha "hello" in a .ml file and then compiling with ocamlc -dparsetree, which showed the particular AST elements I needed to worry about. This seems like it would be necessary even if you’re doing it “by hand,” since you need to know the same information in either case.


#3

Ah, I had been grepping for a value called longident, because that’s the type’s name, but couldn’t find it… lident it is, thanks!