The Atomiser, Part II
So now we have some initial requirements to work with:
- Ability to include a list of valid atoms into a source file.
- Have the Erlang compiler tell us when an atom used is not in the valid list.
- Have the Erlang compiler tell us when an atom in the valid list is not used.
To achieve this I am going to write an Erlang parse transformation module. (A parse transformation takes the already-parsed syntax tree of an Erlang program and (usually) applies some modification to it.)
As an aside, programmers are strongly advised not to engage in parse transformations and no support is offered for problems encountered... but where is the fun in that?
In this case we are not actually going to engage in any transformations - we just want to hook into the compiler and scan the source code for atoms at compile-time.
So without further ado, I present the Atomiser, first draft:
-module(atomiser).
-export([parse_transform/2]).
parse_transform(AST, _Options) ->
io:format("The Atomiser is running.~n"),
AST.
All we are doing at this stage is printing a message and returning the unchanged Abstract Syntax Tree.
Once this atomiser.erl file is compiled into atomiser.beam we can put a parse_transform compiler directive in any source file and the compiler will call the Atomiser's parse_transform function automatically.
-compile({parse_transform, atomiser}).
Since we are already engaging in a highly ill-advised activity, we might as well go the whole way and include this directive into the Atomiser itself. (Only do this after the original version has been compiled, or the compiler will hang when it tries to compile this file.)
-module(atomiser).
-export([parse_transform/2]).
-compile({parse_transform, atomiser}).
parse_transform(AST, _Options) ->
io:format("The Atomiser is running.~n"),
AST.
So when we compile this program we should be informed that the Atomiser is actually running:
1> c(atomiser), l(atomiser).
The Atomiser is running.
{module, atomiser}
So far, so good.
No comments:
Post a Comment