[erlang-questions] how: Building Core Erlang abstract syntax trees

Richard Carlsson richardc@REDACTED
Sat May 31 21:08:02 CEST 2008


Christian S wrote:
> One can use compile:forms/2 to compile core erlang abstract syntax
> trees directly, but what is the suggested way to construct these
> trees?
> 
> There is lib/compile/src/core_parse.* (and especially the records in
> the hrl file), and there is the 'cerl' module which has good edoc. The
> module 'cerl' has node-constructors for the core erlang ast.
>
 > Looking at LFE, it doesnt make use of cerl, it hits the core erlang
 > records directly. Is this an oversight of Robert Virding or the more
 > practical thing to do?

This is for historical reasons. When we started working on Core Erlang,
Robert (and others) preferred working directly with records, while I
preferred using a "proper" abstract datatype (even though it meant
that I couldn't decompose structures using pattern matching). Also,
we had some different ideas regarding how some things such as literals
and variables ought to be represented. So you'll find that the central
parts of the compiler use the records defined in core_parse.hrl, while
cerl_inline and everything in lib/hipe/cerl uses the cerl.erl ADT (which
can be converted to/from the record format).

To ensure that there are no undetected mix-ups between the formats,
the ADT representation uses different tuple tags (the records in
core_parse.hrl all begin with "c_"), and the conversion functions
have to be used.

You can use any representation you like to build your own trees; it's
mostly a matter of programming style. The ADT is better at letting you
not have to distinguish between plain variables and function-variables
except where absolutely necessary.

> Also, Core Erlang allows for annotations, what is the benefits one
> could have from adding these? Static type analysis or can the compiler
> make use of them?

The compiler uses the annotations for various info, you can use them for
analyses etc., and you can pass hooks to lib/hipe/cerl_prettypr.erl to
format core code using HTML markup that depends on annotations (very
useful for visualizing the results of analyses).

     /Richard

PS. The "recursive environment" ADT in lib/compiler/src/rec_env.erl can
be very useful for making transformations. In particular, it makes the
generation of fresh variables easy.

-- 
  "Having users is like optimization: the wise course is to delay it."
    -- Paul Graham



More information about the erlang-questions mailing list