aboutsummaryrefslogtreecommitdiffstats
path: root/system/doc/getting_started/records_macros.xml
blob: bec751fea2387c07931bbb9ec5ab7a7e9eda2b03 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE chapter SYSTEM "chapter.dtd">

<chapter>
  <header>
    <copyright>
      <year>2003</year><year>2013</year>
      <holder>Ericsson AB. All Rights Reserved.</holder>
    </copyright>
    <legalnotice>
      The contents of this file are subject to the Erlang Public License,
      Version 1.1, (the "License"); you may not use this file except in
      compliance with the License. You should have received a copy of the
      Erlang Public License along with this software. If not, it can be
      retrieved online at http://www.erlang.org/.
    
      Software distributed under the License is distributed on an "AS IS"
      basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
      the License for the specific language governing rights and limitations
      under the License.
    
    </legalnotice>

    <title>Records and Macros</title>
    <prepared></prepared>
    <docno></docno>
    <date></date>
    <rev></rev>
    <file>record_macros.xml</file>
  </header>
  <p>Larger programs are usually written as a collection of files with
    a well-defined interface between the various parts.</p>

  <section>
    <title>The Larger Example Divided into Several Files</title>
    <p>To illustrate this, the messenger example from
      the previous section is divided into the following five files:</p>
    <list type="bulleted">
      <item>
      <p><c>mess_config.hrl</c></p>
      <p>Header file for configuration data</p></item>
      <item>
      <p><c>mess_interface.hrl</c></p>
      <p>Interface definitions between the client and the messenger</p></item>
      <item>
      <p><c>user_interface.erl</c></p>
      <p>Functions for the user interface</p></item>
      <item>
      <p><c>mess_client.erl</c></p>
      <p>Functions for the client side of the messenger</p></item>
      <item>
      <p><c>mess_server.erl</c></p>
      <p>Functions for the server side of the messenger</p></item>
    </list>
    <p>While doing this, the message passing interface between the shell,
      the client, and the server is cleaned up and is defined
      using <em>records</em>. Also, <em>macros</em> are introduced:</p>
    <code type="none">
%%%----FILE mess_config.hrl----

%%% Configure the location of the server node,
-define(server_node, messenger@super).

%%%----END FILE----</code>
    <code type="none">
%%%----FILE mess_interface.hrl----

%%% Message interface between client and server and client shell for
%%% messenger program 

%%%Messages from Client to server received in server/1 function.
-record(logon,{client_pid, username}).
-record(message,{client_pid, to_name, message}).
%%% {'EXIT', ClientPid, Reason}  (client terminated or unreachable.

%%% Messages from Server to Client, received in await_result/0 function 
-record(abort_client,{message}).
%%% Messages are: user_exists_at_other_node, 
%%%               you_are_not_logged_on
-record(server_reply,{message}).
%%% Messages are: logged_on
%%%               receiver_not_found
%%%               sent  (Message has been sent (no guarantee)
%%% Messages from Server to Client received in client/1 function
-record(message_from,{from_name, message}).

%%% Messages from shell to Client received in client/1 function
%%% spawn(mess_client, client, [server_node(), Name])
-record(message_to,{to_name, message}).
%%% logoff

%%%----END FILE----</code>
    <code type="none">
%%%----FILE user_interface.erl----

%%% User interface to the messenger program
%%% login(Name)
%%%     One user at a time can log in from each Erlang node in the
%%%     system messenger: and choose a suitable Name. If the Name
%%%     is already logged in at another node or if someone else is
%%%     already logged in at the same node, login will be rejected
%%%     with a suitable error message.

%%% logoff()
%%%     Logs off anybody at that node

%%% message(ToName, Message)
%%%     sends Message to ToName. Error messages if the user of this 
%%%     function is not logged on or if ToName is not logged on at
%%%     any node.

-module(user_interface).
-export([logon/1, logoff/0, message/2]).
-include("mess_interface.hrl").
-include("mess_config.hrl").

logon(Name) ->
    case whereis(mess_client) of 
        undefined ->
            register(mess_client, 
                     spawn(mess_client, client, [?server_node, Name]));
        _ -> already_logged_on
    end.

logoff() ->
    mess_client ! logoff.

message(ToName, Message) ->
    case whereis(mess_client) of % Test if the client is running
        undefined ->
            not_logged_on;
        _ -> mess_client ! #message_to{to_name=ToName, message=Message},
             ok
end.

%%%----END FILE----</code>
    <code type="none">
%%%----FILE mess_client.erl----

%%% The client process which runs on each user node

-module(mess_client).
-export([client/2]).
-include("mess_interface.hrl").

client(Server_Node, Name) ->
    {messenger, Server_Node} ! #logon{client_pid=self(), username=Name},
    await_result(),
    client(Server_Node).

client(Server_Node) ->
    receive
        logoff ->
            exit(normal);
        #message_to{to_name=ToName, message=Message} ->
            {messenger, Server_Node} ! 
                #message{client_pid=self(), to_name=ToName, message=Message},
            await_result();
        {message_from, FromName, Message} ->
            io:format("Message from ~p: ~p~n", [FromName, Message])
    end,
    client(Server_Node).

%%% wait for a response from the server
await_result() ->
    receive
        #abort_client{message=Why} ->
            io:format("~p~n", [Why]),
            exit(normal);
        #server_reply{message=What} ->
            io:format("~p~n", [What])
    after 5000 ->
            io:format("No response from server~n", []),
            exit(timeout)
    end.

%%%----END FILE---</code>
    <code type="none">
%%%----FILE mess_server.erl----

%%% This is the server process of the messenger service

-module(mess_server).
-export([start_server/0, server/0]).
-include("mess_interface.hrl").

server() ->
    process_flag(trap_exit, true),
    server([]).

%%% the user list has the format [{ClientPid1, Name1},{ClientPid22, Name2},...]
server(User_List) ->
    io:format("User list = ~p~n", [User_List]),
    receive
        #logon{client_pid=From, username=Name} ->
            New_User_List = server_logon(From, Name, User_List),
            server(New_User_List);
        {'EXIT', From, _} ->
            New_User_List = server_logoff(From, User_List),
            server(New_User_List);
        #message{client_pid=From, to_name=To, message=Message} ->
            server_transfer(From, To, Message, User_List),
            server(User_List)
    end.

%%% Start the server
start_server() ->
    register(messenger, spawn(?MODULE, server, [])).

%%% Server adds a new user to the user list
server_logon(From, Name, User_List) ->
    %% check if logged on anywhere else
    case lists:keymember(Name, 2, User_List) of
        true ->
            From ! #abort_client{message=user_exists_at_other_node},
            User_List;
        false ->
            From ! #server_reply{message=logged_on},
            link(From),
            [{From, Name} | User_List]        %add user to the list
    end.

%%% Server deletes a user from the user list
server_logoff(From, User_List) ->
    lists:keydelete(From, 1, User_List).

%%% Server transfers a message between user
server_transfer(From, To, Message, User_List) ->
    %% check that the user is logged on and who he is
    case lists:keysearch(From, 1, User_List) of
        false ->
            From ! #abort_client{message=you_are_not_logged_on};
        {value, {_, Name}} ->
            server_transfer(From, Name, To, Message, User_List)
    end.
%%% If the user exists, send the message
server_transfer(From, Name, To, Message, User_List) ->
    %% Find the receiver and send the message
    case lists:keysearch(To, 2, User_List) of
        false ->
            From ! #server_reply{message=receiver_not_found};
        {value, {ToPid, To}} ->
            ToPid ! #message_from{from_name=Name, message=Message}, 
            From !  #server_reply{message=sent} 
    end.

%%%----END FILE---</code>
  </section>

  <section>
    <title>Header Files</title>
    <p>As shown above, some files have extension <c>.hrl</c>. These
      are header files that are included in the <c>.erl</c> files by:</p>
    <code type="none">
-include("File_Name").</code>
    <p>for example:</p>
    <code type="none">
-include("mess_interface.hrl").</code>
    <p>In the case above the file is fetched from the same directory as
      all the other files in the messenger example. (*manual*).</p>
    <p>.hrl files can contain any valid Erlang code but are most often
      used for record and macro definitions.</p>
  </section>

  <section>
    <title>Records</title>
    <p>A record is defined as:</p>
    <code type="none">
-record(name_of_record,{field_name1, field_name2, field_name3, ......}).</code>
    <p>For example:</p>
    <code type="none">
-record(message_to,{to_name, message}).</code>
    <p>This is equivalent to:</p>
    <code type="none">
{message_to, To_Name, Message}</code>
    <p>Creating a record is best illustrated by an example:</p>
    <code type="none">
#message_to{message="hello", to_name=fred)</code>
    <p>This creates:</p>
    <code type="none">
{message_to, fred, "hello"}</code>
    <p>Notice that you do not have to worry about the order you assign
      values to the various parts of the records when you create it.
      The advantage of using records is that by placing their
      definitions in header files you can conveniently define
      interfaces that are easy to change. For example, if you want to
      add a new field to the record, you only have to change
      the code where the new field is used and not at every place
      the record is referred to. If you leave out a field when creating
      a record, it gets the value of the atom <c>undefined</c>. (*manual*)</p>
    <p>Pattern matching with records is very similar to creating
      records. For example, inside a <c>case</c> or <c>receive</c>:</p>
    <code type="none">
#message_to{to_name=ToName, message=Message} -></code>
    <p>This is the same as:</p>
    <code type="none">
{message_to, ToName, Message}</code>
  </section>

  <section>
    <title>Macros</title>
    <p>Another thing that has been added to the messenger is a macro.
      The file <c>mess_config.hrl</c> contains the definition:</p>
    <code type="none">
%%% Configure the location of the server node,
-define(server_node, messenger@super).</code>
    <p>This file is included in <c>mess_server.erl</c>:</p>
    <code type="none">
-include("mess_config.hrl").</code>
    <p>Every occurrence of <c>?server_node</c> in <c>mess_server.erl</c>
      is now replaced by <c>messenger@super</c>.</p>
    <p>A macro is also used when spawning the server process:</p>
    <code type="none">
spawn(?MODULE, server, [])</code>
    <p>This is a standard macro (that is, defined by the system, not by
      the user). <c>?MODULE</c> is always replaced by the name of the
      current module (that is, the <c>-module</c> definition near the start
      of the file). There are more advanced ways of using macros with,
      for example, parameters (*manual*).</p>
    <p>The three Erlang (<c>.erl</c>) files in the messenger example are
      individually compiled into object code file (<c>.beam</c>).
      The Erlang system loads and links these files into the system
      when they are referred to during execution of the code. In this
      case, they are simply put in our current working directory
      (that is, the place you have done "cd" to).
      There are ways of putting the <c>.beam</c> files in other
      directories.</p>
    <p>In the messenger example, no assumptions have been made about
      what the message being sent is. It can be any valid Erlang term.</p>
  </section>
</chapter>