I would like to transform an erl_parse:abstract_form() representation into an erl_syntax:syntaxTree(). Is there a straightforward way to achieve this?
My main reason for wanting this transformation is to annotate AST nodes with typing information. It seems that using functions such as erl_syntax:set_ann/2, erl_syntax:get_ann/1, etc., is the cleanest way to write/read custom annotations to/from syntaxTree() nodes. Is my understanding correct?
One worry I have is this. The docs for erl_syntax state that developers should assume nothing about the internal representation of syntaxTree(), as it could change without notice. Would this mean that pattern matching against tree nodes (like in parse transformations) is discouraged? Using the functions provided by erl_syntax to create AST nodes is sensible in my head. Yet, adopting erl_syntax:type/1, erl_syntax:function_name/1, etc., for controlling the program flow or reading node information seems tedious and inelegant by comparison to pattern matching. Is there a better solution that I have missed?
Lastly, I've tried adding custom annotations to abstract_form() trees using the erl_anno module in lieu of using syntaxTree() since the latter representation is very verbose. This approach is hacky at best, however. I gather from the Erlang docs and implementation of erl_anno that this is not a correct way of decorating abstract_form() nodes with custom annotations. The only annotations allowed by erl_anno are column, location, text, line, file, generated, and record. Is this a correct interpretation?
The functions in
erl_syntaxcan work directly on the data structures returned byerl_parse. Only if you want to go in the other direction do you have to do a (lossy) conversion by callingerl_syntax:revert().A special case is if you have a list of
erl_parseforms. This doesn't in itself work as a syntax tree, so you can't e.g. pass the list directly intoerl_syntax:type(), but you can pass it intoerl_syntax:form_list()and from there on it can be operated on like any other abstract syntax tree.To make your code less verbose and use patterns to deconstruct and construct syntax trees, check out the
merlmodule: https://www.erlang.org/doc/man/merl