auto-generated record access functions

Ulf Wiger (AL/EAB) <>
Tue Apr 18 18:35:25 CEST 2006


I've written a small(-ish) parse transform that 
generates code for accessing exported records.

I did read through ROK's abstract patterns proposal
once more, but decided that it would be too much to 
try to implement _that_. The current hack does use 
function names that are somewhat similar to ROK's 
abstract patterns, but I don't think that will be a 
problem (mainly because I don't envision that anyone
would use this stuff if the abstract patterns were 
available.)

The idea is to use records as before, but for module-
local use. For outside callers, records are 'exported'
by including a -export_records([RecName]) directive.
The following code extract illustrates the kind of 
code laid out by the parse_transform:

-module(test).
-compile({parse_transform, exprecs}).
-record(a, {a, b, c}).
-export_records([a]).

%%% generated code
-export(['#new-a'/0, '#new-a'/1,
         '#get-a'/2, '#set-a'/2,
         '#info-a'/1]).

'#new-a'() -> #a{}.
'#new-a'(Vals) -> '#set-a'(Vals, #a{}).

'#get-a'(Attrs, R) when is_list(Attrs) ->
    ['#get-a'(A, R) || A <- Attrs];
'#get-a'(a, R) -> R#a.a;
'#get-a'(b, R) -> R#a.b;
'#get-a'(c, R) -> R#a.c.

'#set-a'(Vals, Rec) ->
    F = fun ([], R, _F1) -> R;
            ([{a, V} | T], R, F1) -> F1(T, R#a{a = V}, F1);
            ([{b, V} | T], R, F1) -> F1(T, R#a{b = V}, F1);
            ([{c, V} | T], R, F1) -> F1(T, R#a{c = V}, F1)
        end,
    F(Vals, Rec, F).

'#info-a'(fields) -> record_info(fields, a).

%%% end generated code


A short shell dialogue to illustrate the use:

Eshell V5.4.12  (abort with ^G)
1> test:'#new-a'().
{a,undefined,undefined,undefined}
2> test:'#set-a'([{a,1},{c,3}], v(1)).
{a,1,undefined,3}
3> test:'#set-a'([{b,2}], v(2)).      
{a,1,2,3}
4> test:'#get-a'(b, v(3)).
2
5> test:'#get-a'([a,c], v(3)).
[1,3]
6> test:'#info-a'(fields).
[a,b,c]


Parse transformery attached. It's based on the stools_id_trans module
that I posted a while back, but with improved error handling (controlled
errors in the parse_transform module are reported as regular compilation
errors.)

BR,
Ulf W
-------------- next part --------------
A non-text attachment was scrubbed...
Name: exprecs.erl
Type: application/octet-stream
Size: 9558 bytes
Desc: exprecs.erl
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20060418/ecf4d534/attachment.obj>


More information about the erlang-questions mailing list