chiark / gitweb /
b4e80ca908b33ab162478b35d190d08ba724acd7
[sod] / doc / concepts.tex
1 %%% -*-latex-*-
2 %%%
3 %%% Conceptual background
4 %%%
5 %%% (c) 2015 Straylight/Edgeware
6 %%%
7
8 %%%----- Licensing notice ---------------------------------------------------
9 %%%
10 %%% This file is part of the Sensible Object Design, an object system for C.
11 %%%
12 %%% SOD is free software; you can redistribute it and/or modify
13 %%% it under the terms of the GNU General Public License as published by
14 %%% the Free Software Foundation; either version 2 of the License, or
15 %%% (at your option) any later version.
16 %%%
17 %%% SOD is distributed in the hope that it will be useful,
18 %%% but WITHOUT ANY WARRANTY; without even the implied warranty of
19 %%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 %%% GNU General Public License for more details.
21 %%%
22 %%% You should have received a copy of the GNU General Public License
23 %%% along with SOD; if not, write to the Free Software Foundation,
24 %%% Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25
26 \chapter{Concepts} \label{ch:concepts}
27
28 %%%--------------------------------------------------------------------------
29 \section{Operational model} \label{sec:concepts.model}
30
31 The Sod translator runs as a preprocessor, similar in nature to the
32 traditional Unix \man{lex}{1} and \man{yacc}{1} tools.  The translator reads
33 a \emph{module} file containing class definitions and other information, and
34 writes C~source and header files.  The source files contain function
35 definitions and static tables which are fed directly to a C~compiler; the
36 header files contain declarations for functions and data structures, and are
37 included by source files -- whether hand-written or generated by Sod -- which
38 makes use of the classes defined in the module.
39
40 Sod is not like \Cplusplus: it makes no attempt to `enhance' the C language
41 itself.  Sod module files describe classes, messages, methods, slots, and
42 other kinds of object-system things, and some of these descriptions need to
43 contain C code fragments, but this code is entirely uninterpreted by the Sod
44 translator.\footnote{%
45   As long as a code fragment broadly follows C's lexical rules, and properly
46   matches parentheses, brackets, and braces, the Sod translator will copy it
47   into its output unchanged.  It might, in fact, be some other kind of C-like
48   language, such as Objective~C or \Cplusplus.  Or maybe even
49   Objective~\Cplusplus, because if having an object system is good, then
50   having three must be really awesome.} %
51
52 The Sod translator is not a closed system.  It is written in Common Lisp, and
53 can load extension modules which add new input syntax, output formats, or
54 altered behaviour.  The interface for writing such extensions is described in
55 \xref{p:lisp}.  Extensions can change almost all details of the Sod object
56 system, so the material in this manual must be read with this in mind: this
57 manual describes the base system as provided in the distribution.
58
59 %%%--------------------------------------------------------------------------
60 \section{Modules} \label{sec:concepts.modules}
61
62 A \emph{module} is the top-level syntactic unit of input to the Sod
63 translator.  As described above, given an input module, the translator
64 generates C source and header files.
65
66 A module can \emph{import} other modules.  This makes the type names and
67 classes defined in those other modules available to class definitions in the
68 importing module.  Sod's module system is intentionally very simple.  There
69 are no private declarations or attempts to hide things.
70
71 As well as importing existing modules, a module can include a number of
72 different kinds of \emph{items}:
73 \begin{itemize}
74 \item \emph{class definitions} describe new classes, possibly in terms of
75   existing classes;
76 \item \emph{type name declarations} introduce new type names to Sod's
77   parser;\footnote{%
78     This is unfortunately necessary because C syntax, upon which Sod's input
79     language is based for obvious reasons, needs to treat type names
80     differently from other kinds of identifiers.} %
81   and
82 \item \emph{code fragments} contain literal C code to be dropped into an
83   appropriate place in an output file.
84 \end{itemize}
85 Each kind of item, and, indeed, a module as a whole, can have a collection of
86 \emph{properties} associated with it.  A property has a \emph{name} and a
87 \emph{value}.  Properties are an open-ended way of attaching additional
88 information to module items, so extensions can make use of them without
89 having to implement additional syntax.
90
91 %%%--------------------------------------------------------------------------
92 \section{Classes, instances, and slots} \label{sec:concepts.classes}
93
94 For the most part, Sod takes a fairly traditional view of what it means to be
95 an object system.
96
97 An \emph{object} maintains \emph{state} and exhibits \emph{behaviour}.  An
98 object's state is maintained in named \emph{slots}, each of which can store a
99 C value of an appropriate (scalar or aggregate) type.  An object's behaviour
100 is stimulated by sending it \emph{messages}.  A message has a name, and may
101 carry a number of arguments, which are C values; sending a message may result
102 in the state of receiving object (or other objects) being changed, and a C
103 value being returned to the sender.
104
105 Every object is a (direct) instance of some \emph{class}.  The class
106 determines which slots its instances have, which messages its instances can
107 be sent, and which methods are invoked when those messages are received.  The
108 Sod translator's main job is to read class definitions and convert them into
109 appropriate C declarations, tables, and functions.  An object cannot
110 (usually) change its direct class, and the direct class of an object is not
111 affected by, for example, the static type of a pointer to it.
112
113
114 \subsection{Superclasses and inheritance}
115 \label{sec:concepts.classes.inherit}
116
117 \subsubsection{Class relationships}
118 Each class has zero or more \emph{direct superclasses}.
119
120 A class with no direct superclasses is called a \emph{root class}.  The Sod
121 runtime library includes a root class named @|SodObject|; making new root
122 classes is somewhat tricky, and won't be discussed further here.
123
124 Classes can have more than one direct superclass, i.e., Sod supports
125 \emph{multiple inheritance}.  A Sod class definition for a class~$C$ lists
126 the direct superclasses of $C$ in a particular order.  This order is called
127 the \emph{local precedence order} of $C$, and the list which consists of $C$
128 follows by $C$'s direct superclasses in local precedence order is called the
129 $C$'s \emph{local precedence list}.
130
131 The multiple inheritance in Sod works similarly to multiple inheritance in
132 Lisp-like languages, such as Common Lisp, EuLisp, Dylan, and Python, which is
133 very different from how multiple inheritance works in \Cplusplus.\footnote{%
134   The latter can be summarized as `badly'.  By default in \Cplusplus, an
135   instance receives an additional copy of superclass's state for each path
136   through the class graph from the instance's direct class to that
137   superclass, though this behaviour can be overridden by declaring
138   superclasses to be @|virtual|.  Also, \Cplusplus\ offers only trivial
139   method combination (\xref{sec:concepts.methods}), leaving programmers to
140   deal with delegation manually and (usually) statically.} %
141
142 If $C$ is a class, then the \emph{superclasses} of $C$ are
143 \begin{itemize}
144 \item $C$ itself, and
145 \item the superclasses of each of $C$'s direct superclasses.
146 \end{itemize}
147 The \emph{proper superclasses} of a class $C$ are the superclasses of $C$
148 except for $C$ itself.  If a class $B$ is a (direct, proper) superclass of
149 $C$, then $C$ is a \emph{(direct, proper) subclass} of $B$.  If $C$ is a root
150 class then the only superclass of $C$ is $C$ itself, and $C$ has no proper
151 superclasses.
152
153 If an object is a direct instance of class~$C$ then the object is also an
154 (indirect) instance of every superclass of $C$.
155
156 If $C$ has a proper superclass $B$, then $B$ is not allowed to have $C$ has a
157 direct superclass.  In different terms, if we construct a graph, whose
158 vertices are classes, and draw an edge from each class to each of its direct
159 superclasses, then this graph must be acyclic.  In yet other terms, the `is a
160 superclass of' relation is a partial order on classes.
161
162 \subsubsection{The class precedence list}
163 This partial order is not quite sufficient for our purposes.  For each class
164 $C$, we shall need to extend it into a total order on $C$'s superclasses.
165 This calculation is called \emph{superclass linearization}, and the result is
166 a \emph{class precedence list}, which lists each of $C$'s superclasses
167 exactly once.  If a superclass $B$ precedes (resp.\ follows) some other
168 superclass $A$ in $C$'s class precedence list, then we say that $B$ is a more
169 (resp.\ less) \emph{specific} superclass of $C$ than $A$ is.
170
171 The superclass linearization algorithm isn't fixed, and extensions to the
172 translator can introduce new linearizations for special effects, but the
173 following properties are expected to hold.
174 \begin{itemize}
175 \item The first class in $C$'s class precedence list is $C$ itself; i.e.,
176   $C$ is always its own most specific superclass.
177 \item If $A$ and $B$ are both superclasses of $C$, and $A$ is a proper
178   superclass of $B$ then $A$ appears after $B$ in $C$'s class precedence
179   list, i.e., $B$ is a more specific superclass of $C$ than $A$ is.
180 \end{itemize}
181 The default linearization algorithm used in Sod is the \emph{C3} algorithm,
182 which has a number of good properties described in~\cite{FIXME:C3}.
183 It works as follows.
184 \begin{itemize}
185 \item A \emph{merge} of some number of input lists is a single list
186   containing each item that is in any of the input lists exactly once, and no
187   other items; if an item $x$ appears before an item $y$ in any input list,
188   then $x$ also appears before $y$ in the merge.  If a collection of lists
189   have no merge then they are said to be \emph{inconsistent}.
190 \item The class precedence list of a class $C$ is a merge of the local
191   precedence list of $C$ together with the class precedence lists of each of
192   $C$'s direct superclasses.
193 \item If there are no such merges, then the definition of $C$ is invalid.
194 \item Suppose that there are multiple candidate merges.  Consider the
195   earliest position in these candidate merges at which they disagree.  The
196   \emph{candidate classes} at this position are the classes appearing at this
197   position in the candidate merges.  Each candidate class must be a
198   superclass of distinct direct superclasses of $C$, since otherwise the
199   candidates would be ordered by their common subclass's class precedence
200   list.  The class precedence list contains, at this position, that candidate
201   class whose subclass appears earliest in $C$'s local precedence order.
202 \end{itemize}
203
204 \subsubsection{Class links and chains}
205 The definition for a class $C$ may distinguish one of its proper superclasses
206 as being the \emph{link superclass} for class $C$.  Not every class need have
207 a link superclass, and the link superclass of a class $C$, if it exists, need
208 not be a direct superclass of $C$.
209
210 Superclass links must obey the following rule: if $C$ is a class, then there
211 must be no three superclasses $X$, $Y$ and~$Z$ of $C$ such that $Z$ is the
212 link superclass of both $X$ and $Y$.  As a consequence of this rule, the
213 superclasses of $C$ can be partitioned into linear \emph{chains}, such that
214 superclasses $A$ and $B$ are in the same chain if and only if one can trace a
215 path from $A$ to $B$ by following superclass links, or \emph{vice versa}.
216
217 Since a class links only to one of its proper superclasses, the classes in a
218 chain are naturally ordered from most- to least-specific.  The least specific
219 class in a chain is called the \emph{chain head}; the most specific class is
220 the \emph{chain tail}.  Chains are often named after their chain head
221 classes.
222
223 \subsection{Names}
224 \label{sec:concepts.classes.names}
225
226 Classes have a number of other attributes:
227 \begin{itemize}
228 \item A \emph{name}, which is a C identifier.  Class names must be globally
229   unique.  The class name is used in the names of a number of associated
230   definitions, to be described later.
231 \item A \emph{nickname}, which is also a C identifier.  Unlike names,
232   nicknames are not required to be globally unique.  If $C$ is any class,
233   then all the superclasses of $C$ must have distinct nicknames.
234 \end{itemize}
235
236
237 \subsection{Slots} \label{sec:concepts.classes.slots}
238
239 Each class defines a number of \emph{slots}.  Much like a structure member, a
240 slot has a \emph{name}, which is a C identifier, and a \emph{type}.  Unlike
241 many other object systems, different superclasses of a class $C$ can define
242 slots with the same name without ambiguity, since slot references are always
243 qualified by the defining class's nickname.
244
245 \subsubsection{Slot initializers}
246 As well as defining slot names and types, a class can also associate an
247 \emph{initial value} with each slot defined by itself or one of its
248 subclasses.  A class $C$ provides an \emph{initialization function} (see
249 \xref{sec:concepts.lifecycle.birth}, and \xref{sec:structures.root.sodclass})
250 which sets the slots of a \emph{direct} instance of the class to the correct
251 initial values.  If several of $C$'s superclasses define initializers for the
252 same slot then the initializer from the most specific such class is used.  If
253 none of $C$'s superclasses define an initializer for some slot then that slot
254 will be left uninitialized.
255
256 The initializer for a slot with scalar type may be any C expression.  The
257 initializer for a slot with aggregate type must contain only constant
258 expressions if the generated code is expected to be processed by a
259 implementation of C89.  Initializers will be evaluated once each time an
260 instance is initialized.
261
262 Slots are initialized in reverse-precedence order of their defining classes;
263 i.e., slots defined by a less specific superclass are initialized earlier
264 than slots defined by a more specific superclass.  Slots defined by the same
265 class are initialized in the order in which they appear in the class
266 definition.
267
268 The initializer for a slot may refer to other slots in the same object, via
269 the @|me| pointer: in an initializer for a slot defined by a class $C$, @|me|
270 has type `pointer to $C$'.  (Note that the type of @|me| depends only on the
271 class which defined the slot, not the class which defined the initializer.)
272
273
274 \subsection{C language integration} \label{sec:concepts.classes.c}
275
276 For each class~$C$, the Sod translator defines a C type, the \emph{class
277 type}, with the same name.  This is the usual type used when considering an
278 object as an instance of class~$C$.  No entire object will normally have a
279 class type,\footnote{%
280   In general, a class type only captures the structure of one of the
281   superclass chains of an instance.  A full instance layout contains multiple
282   chains.  See \xref{sec:structures.layout} for the full details.} %
283 so access to instances is almost always via pointers.
284
285 \subsubsection{Access to slots}
286 The class type for a class~$C$ is actually a structure.  It contains one
287 member for each class in $C$'s superclass chain, named with that class's
288 nickname.  Each of these members is also a structure, containing the
289 corresponding class's slots, one member per slot.  There's nothing special
290 about these slot members: C code can access them in the usual way.
291
292 For example, if @|MyClass| has the nickname @|mine|, and defines a slot @|x|
293 of type @|int|, then the simple function
294 \begin{prog}
295   int get_x(MyClass *m) \{ return (m@->mine.x); \}
296 \end{prog}
297 will extract the value of @|x| from an instance of @|MyClass|.
298
299 All of this means that there's no such thing as `private' or `protected'
300 slots.  If you want to hide implementation details, the best approach is to
301 stash them in a dynamically allocated private structure, and leave a pointer
302 to it in a slot.  (This will also help preserve binary compatibility, because
303 the private structure can grow more members as needed.  See
304 \xref{sec:fixme.compatibility} for more details.
305
306 \subsubsection{Class objects}
307 In Sod's object system, classes are objects too.  Therefore classes are
308 themselves instances; the class of a class is called a \emph{metaclass}.  The
309 consequences of this are explored in \xref{sec:concepts.metaclasses}.  The
310 \emph{class object} has the same name as the class, suffixed with
311 `@|__class|'\footnote{%
312   This is not quite true.  @|$C$__class| is actually a macro.  See
313   \xref{sec:structures.layout.additional} for the gory details.} %
314 and its type is usually @|SodClass|; @|SodClass|'s nickname is @|cls|.
315
316 A class object's slots contain or point to useful information, tables and
317 functions for working with that class's instances.  (The @|SodClass| class
318 doesn't define any messages, so it doesn't have any methods.  In Sod, a class
319 slot containing a function pointer is not at all the same thing as a method.)
320
321 \subsubsection{Conversions}
322 Suppose one has a value of type pointer to class type of some class~$C$, and
323 wants to convert it to a pointer to class type of some other class~$B$.
324 There are three main cases to distinguish.
325 \begin{itemize}
326 \item If $B$ is a superclass of~$C$, in the same chain, then the conversion
327   is an \emph{in-chain upcast}.  The conversion can be performed using the
328   appropriate generated upcast macro (see below), or by simply casting the
329   pointer, using C's usual cast operator (or the \Cplusplus\ @|static_cast<>|
330   operator).
331 \item If $B$ is a superclass of~$C$, in a different chain, then the
332   conversion is a \emph{cross-chain upcast}.  The conversion is more than a
333   simple type change: the pointer value must be adjusted.  If the direct
334   class of the instance in question is not known, the conversion will require
335   a lookup at runtime to find the appropriate offset by which to adjust the
336   pointer.  The conversion can be performed using the appropriate generated
337   upcast macro (see below); the general case is handled by the macro
338   \descref{SOD_XCHAIN}{mac}.
339 \item If $B$ is a subclass of~$C$ then the conversion is an \emph{upcast};
340   otherwise the conversion is a~\emph{cross-cast}.  In either case, the
341   conversion can fail: the object in question might not be an instance of~$B$
342   at all.  The macro \descref{SOD_CONVERT}{mac} and the function
343   \descref{sod_convert}{fun} perform general conversions.  They return a null
344   pointer if the conversion fails.  (There are therefore your analogue to the
345   \Cplusplus @|dynamic_cast<>| operator.)
346 \end{itemize}
347 The Sod translator generates macros for performing both in-chain and
348 cross-chain upcasts.  For each class~$C$, and each proper superclass~$B$
349 of~$C$, a macro is defined: given an argument of type pointer to class type
350 of~$C$, it returns a pointer to the same instance, only with type pointer to
351 class type of~$B$, adjusted as necessary in the case of a cross-chain
352 conversion.  The macro is named by concatenating
353 \begin{itemize}
354 \item the name of class~$C$, in upper case,
355 \item the characters `@|__CONV_|', and
356 \item the nickname of class~$B$, in upper case;
357 \end{itemize}
358 e.g., if $C$ is named @|MyClass|, and $B$'s name is @|SuperClass| with
359 nickname @|super|, then the macro @|MYCLASS__CONV_SUPER| converts a
360 @|MyClass~*| to a @|SuperClass~*|.  See
361 \xref{sec:structures.layout.additional} for the formal description.
362
363 %%%--------------------------------------------------------------------------
364 \section{Keyword arguments} \label{sec:concepts.keywords}
365
366 In standard C, the actual arguments provided to a function are matched up
367 with the formal arguments given in the function definition according to their
368 ordering in a list.  Unless the (rather cumbersome) machinery for dealing
369 with variable-length argument tails (@|<stdarg.h>|) is used, exactly the
370 correct number of arguments must be supplied, and in the correct order.
371
372 A \emph{keyword argument} is matched by its distinctive \emph{name}, rather
373 than by its position in a list.  Keyword arguments may be \emph{omitted},
374 causing some default behaviour by the function.  A function can detect
375 whether a particular keyword argument was supplied: so the default behaviour
376 need not be the same as that caused by any specific value of the argument.
377
378 Keyword arguments can be provided in three ways.
379 \begin{enumerate}
380 \item Directly, as a variable-length argument tail, consisting (for the most
381   part) of alternating keyword names, as pointers to null-terminated strings,
382   and argument values, and terminated by a null pointer.  This is somewhat
383   error-prone, and the support library defines some macros which help ensure
384   that keyword argument lists are well formed.
385 \item Indirectly, through a @|va_list| object capturing a variable-length
386   argument tail passed to some other function.  Such indirect argument tails
387   have the same structure as the direct argument tails described above.
388   Because @|va_list| objects are hard to copy, the keyword-argument support
389   library consistently passes @|va_list| objects \emph{by reference}
390   throughout its programming interface.
391 \item Indirectly, through a vector of @|struct kwval| objects, each of which
392   contains a keyword name, as a pointer to a null-terminated string, and the
393   \emph{address} of a corresponding argument value.  (This indirection is
394   necessary so that the items in the vector can be of uniform size.)
395   Argument vectors are rather inconvenient to use, but are the only practical
396   way in which a caller can decide at runtime which arguments to include in a
397   call, which is useful when writing wrapper functions.
398 \end{enumerate}
399
400 Keyword arguments are provided as a general feature for C functions.
401 However, Sod has special support for messages which accept keyword arguments
402 (\xref{sec:concepts.methods.keywords}); and they play an essential role in
403 the instance construction protocol (\xref{sec:concepts.lifecycle.birth}).
404
405 %%%--------------------------------------------------------------------------
406 \section{Messages and methods} \label{sec:concepts.methods}
407
408 Objects can be sent \emph{messages}.  A message has a \emph{name}, and
409 carries a number of \emph{arguments}.  When an object is sent a message, a
410 function, determined by the receiving object's class, is invoked, passing it
411 the receiver and the message arguments.  This function is called the
412 class's \emph{effective method} for the message.  The effective method can do
413 anything a C function can do, including reading or updating program state or
414 object slots, sending more messages, calling other functions, issuing system
415 calls, or performing I/O; if it finishes, it may return a value, which is
416 returned in turn to the message sender.
417
418 The set of messages an object can receive, characterized by their names,
419 argument types, and return type, is determined by the object's class.  Each
420 class can define new messages, which can be received by any instance of that
421 class.  The messages defined by a single class must have distinct names:
422 there is no `function overloading'.  As with slots
423 (\xref{sec:concepts.classes.slots}), messages defined by distinct classes are
424 always distinct, even if they have the same names: references to messages are
425 always qualified by the defining class's name or nickname.
426
427 Messages may take any number of arguments, of any non-array value type.
428 Since message sends are effectively function calls, arguments of array type
429 are implicitly converted to values of the corresponding pointer type.  While
430 message definitions may ascribe an array type to an argument, the formal
431 argument will have pointer type, as is usual for C functions.  A message may
432 accept a variable-length argument suffix, denoted @|\dots|.
433
434 A class definition may include \emph{direct methods} for messages defined by
435 it or any of its superclasses.
436
437 Like messages, direct methods define argument lists and return types, but
438 they may also have a \emph{body}, and a \emph{role}.
439
440 A direct method need not have the same argument list or return type as its
441 message.  The acceptable argument lists and return types for a method depend
442 on the message, in particular its method combination
443 (\xref{sec:concepts.methods.combination}), and the method's role.
444
445 A direct method body is a block of C code, and the Sod translator usually
446 defines, for each direct method, a function with external linkage, whose body
447 contains a copy of the direct method body.  Within the body of a direct
448 method defined for a class $C$, the variable @|me|, of type pointer to class
449 type of $C$, refers to the receiving object.
450
451
452 \subsection{Effective methods and method combinations}
453 \label{sec:concepts.methods.combination}
454
455 For each message a direct instance of a class might receive, there is a set
456 of \emph{applicable methods}, which are exactly the direct methods defined on
457 the object's class and its superclasses.  These direct methods are combined
458 together to form the \emph{effective method} for that particular class and
459 message.  Direct methods can be combined into an effective method in
460 different ways, according to the \emph{method combination} specified by the
461 message.  The method combination determines which direct method roles are
462 acceptable, and, for each role, the appropriate argument lists and return
463 types.
464
465 One direct method, $M$, is said to be more (resp.\ less) \emph{specific} than
466 another, $N$, with respect to a receiving class~$C$, if the class defining
467 $M$ is a more (resp.\ less) specific superclass of~$C$ than the class
468 defining $N$.
469
470 \subsubsection{The standard method combination}
471 The default method combination is called the \emph{standard method
472 combination}; other method combinations are useful occasionally for special
473 effects.  The standard method combination accepts four direct method roles,
474 called `primary' (the default), @|before|, @|after|, and @|around|.
475
476 All direct methods subject to the standard method combination must have
477 argument lists which \emph{match} the message's argument list:
478 \begin{itemize}
479 \item the method's arguments must have the same types as the message, though
480   the arguments may have different names; and
481 \item if the message accepts a variable-length argument suffix then the
482   direct method must instead have a final argument of type @|va_list|.
483 \end{itemize}
484 Primary and @|around| methods must have the same return type as the message;
485 @|before| and @|after| methods must return @|void| regardless of the
486 message's return type.
487
488 If there are no applicable primary methods then no effective method is
489 constructed: the vtables contain null pointers in place of pointers to method
490 entry functions.
491
492 The effective method for a message with standard method combination works as
493 follows.
494 \begin{enumerate}
495
496 \item If any applicable methods have the @|around| role, then the most
497   specific such method, with respect to the class of the receiving object, is
498   invoked.
499
500   Within the body of an @|around| method, the variable @|next_method| is
501   defined, having pointer-to-function type.  The method may call this
502   function, as described below, any number of times.
503
504   If there any remaining @|around| methods, then @|next_method| invokes the
505   next most specific such method, returning whichever value that method
506   returns; otherwise the behaviour of @|next_method| is to invoke the before
507   methods (if any), followed by the most specific primary method, followed by
508   the @|around| methods (if any), and to return whichever value was returned
509   by the most specific primary method, as described in the following items.
510   That is, the behaviour of the least specific @|around| method's
511   @|next_method| function is exactly the behaviour that the effective method
512   would have if there were no @|around| methods.  Note that if the
513   least-specific @|around| method calls its @|next_method| more than once
514   then the whole sequence of @|before|, primary, and @|after| methods occurs
515   multiple times.
516
517   The value returned by the most specific @|around| method is the value
518   returned by the effective method.
519
520 \item If any applicable methods have the @|before| role, then they are all
521   invoked, starting with the most specific.
522
523 \item The most specific applicable primary method is invoked.
524
525   Within the body of a primary method, the variable @|next_method| is
526   defined, having pointer-to-function type.  If there are no remaining less
527   specific primary methods, then @|next_method| is a null pointer.
528   Otherwise, the method may call the @|next_method| function any number of
529   times.
530
531   The behaviour of the @|next_method| function, if it is not null, is to
532   invoke the next most specific applicable primary method, and to return
533   whichever value that method returns.
534
535   If there are no applicable @|around| methods, then the value returned by
536   the most specific primary method is the value returned by the effective
537   method; otherwise the value returned by the most specific primary method is
538   returned to the least specific @|around| method, which called it via its
539   own @|next_method| function.
540
541 \item If any applicable methods have the @|after| role, then they are all
542   invoked, starting with the \emph{least} specific.  (Hence, the most
543   specific @|after| method is invoked with the most `afterness'.)
544
545 \end{enumerate}
546
547 A typical use for @|around| methods is to allow a base class to set up the
548 dynamic environment appropriately for the primary methods of its subclasses,
549 e.g., by claiming a lock, and restore it afterwards.
550
551 The @|next_method| function provided to methods with the primary and
552 @|around| roles accepts the same arguments, and returns the same type, as the
553 message, except that one or two additional arguments are inserted at the
554 front of the argument list.  The first additional argument is always the
555 receiving object, @|me|.  If the message accepts a variable argument suffix,
556 then the second addition argument is a @|va_list|; otherwise there is no
557 second additional argument; otherwise, In the former case, a variable
558 @|sod__master_ap| of type @|va_list| is defined, containing a separate copy
559 of the argument pointer (so the method body can process the variable argument
560 suffix itself, and still pass a fresh copy on to the next method).
561
562 A method with the primary or @|around| role may use the convenience macro
563 @|CALL_NEXT_METHOD|, which takes no arguments itself, and simply calls
564 @|next_method| with appropriate arguments: the receiver @|me| pointer, the
565 argument pointer @|sod__master_ap| (if applicable), and the method's
566 arguments.  If the method body has overwritten its formal arguments, then
567 @|CALL_NEXT_METHOD| will pass along the updated values, rather than the
568 original ones.
569
570 A primary or @|around| method which invokes its @|next_method| function is
571 said to \emph{extend} the message behaviour; a method which does not invoke
572 its @|next_method| is said to \emph{override} the behaviour.  Note that a
573 method may make a decision to override or extend at runtime.
574
575 \subsubsection{Aggregating method combinations}
576 A number of other method combinations are provided.  They are called
577 `aggregating' method combinations because, instead of invoking just the most
578 specific primary method, as the standard method combination does, they invoke
579 the applicable primary methods in turn and aggregate the return values from
580 each.
581
582 The aggregating method combinations accept the same four roles as the
583 standard method combination, and @|around|, @|before|, and @|after| methods
584 work in the same way.
585
586 The aggregating method combinations provided are as follows.
587 \begin{description} \let\makelabel\code
588 \item[progn] The message must return @|void|.  The applicable primary methods
589   are simply invoked in turn, most specific first.
590 \item[sum] The message must return a numeric type.\footnote{%
591     The Sod translator does not check this, since it doesn't have enough
592     insight into @|typedef| names.} %
593   The applicable primary methods are invoked in turn, and their return values
594   added up.  The final result is the sum of the individual values.
595 \item[product] The message must return a numeric type.  The applicable
596   primary methods are invoked in turn, and their return values multiplied
597   together.  The final result is the product of the individual values.
598 \item[min] The message must return a scalar type.  The applicable primary
599   methods are invoked in turn.  The final result is the smallest of the
600   individual values.
601 \item[max] The message must return a scalar type.  The applicable primary
602   methods are invoked in turn.  The final result is the largest of the
603   individual values.
604 \item[and] The message must return a scalar type.  The applicable primary
605   methods are invoked in turn.  If any method returns zero then the final
606   result is zero and no further methods are invoked.  If all of the
607   applicable primary methods return nonzero, then the final result is the
608   result of the last primary method.
609 \item[or] The message must return a scalar type.  The applicable primary
610   methods are invoked in turn.  If any method returns nonzero then the final
611   result is that nonzero value and no further methods are invoked.  If all of
612   the applicable primary methods return zero, then the final result is zero.
613 \end{description}
614
615 There is also a @|custom| aggregating method combination, which is described
616 in \xref{sec:fixme.custom-aggregating-method-combination}.
617
618
619 \subsection{Messages with keyword arguments}
620 \label{sec:concepts.methods.keywords}
621
622 A message or a direct method may declare that it accepts keyword arguments.
623 A message which accepts keyword arguments is called a \emph{keyword message};
624 a direct method which accepts keyword arguments is called a \emph{keyword
625 method}.
626
627 While method combinations may set their own rules, usually keyword methods
628 can only be defined on keyword messages, and all methods defined on a keyword
629 message must be keyword methods.  The direct methods defined on a keyword
630 message may differ in the keywords they accept, both from each other, and
631 from the message.  If two superclasses of some common class both define
632 keyword methods on the same message, and the methods both accept a keyword
633 argument with the same name, then these two keyword arguments must also have
634 the same type.  Different applicable methods may declare keyword arguments
635 with the same name but different defaults; see below.
636
637 The keyword arguments acceptable in a message sent to an object are the
638 keywords listed in the message definition, together with all of the keywords
639 accepted by any applicable method.  There is no easy way to determine at
640 runtime whether a particular keyword is acceptable in a message to a given
641 instance.
642
643 At runtime, a direct method which accepts one or more keyword arguments
644 receives an additional argument named @|suppliedp|.  This argument is a small
645 structure.  For each keyword argument named $k$ accepted by the direct
646 method, @|suppliedp| contains a one-bit-wide bitfield member of type
647 @|unsigned|, also named $k$.  If a keyword argument named $k$ was passed in
648 the message, then @|suppliedp.$k$| is one, and $k$ contains the argument
649 value; otherwise @|suppliedp.$k$| is zero, and $k$ contains the default value
650 from the direct method definition if there was one, or an unspecified value
651 otherwise.
652
653 %%%--------------------------------------------------------------------------
654 \section{The object lifecycle} \label{sec:concepts.lifecycle}
655
656 \subsection{Creation} \label{sec:concepts.lifecycle.birth}
657
658 Construction of a new instance of a class involves three steps.
659 \begin{enumerate}
660 \item \emph{Allocation} arranges for there to be storage space for the
661   instance's slots and associated metadata.
662 \item \emph{Imprinting} fills in the instance's metadata, associating the
663   instance with its class.
664 \item \emph{Initialization} stores appropriate initial values in the
665   instance's slots, and maybe links it into any external data structures as
666   necessary.
667 \end{enumerate}
668 The \descref{SOD_DECL}[macro]{mac} handles constructing instances with
669 automatic storage duration (`on the stack').  Similarly, the
670 \descref{SOD_MAKE}[macro]{mac} and the \descref{sod_make}{fun} and
671 \descref{sod_makev}{fun} functions construct instances allocated from the
672 standard @|malloc| heap.  Programmers can add support for other allocation
673 strategies by using the \descref{SOD_INIT}[macro]{mac} and the
674 \descref{sod_init}{fun} and \descref{sod_initv}{fun} functions, which package
675 up imprinting and initialization.
676
677 \subsubsection{Allocation}
678 Instances of most classes (specifically including those classes defined by
679 Sod itself) can be held in any storage of sufficient size.  The in-memory
680 layout of an instance of some class~$C$ is described by the type @|struct
681 $C$__ilayout|, and if the relevant class is known at compile time then the
682 best way to discover the layout size is with the @|sizeof| operator.  Failing
683 that, the size required to hold an instance of $C$ is available in a slot in
684 $C$'s class object, as @|$C$__class@->cls.initsz|.
685
686 It is not in general sufficient to declare, or otherwise allocate, an object
687 of the class type $C$.  The class type only describes a single chain of the
688 object's layout.  It is nearly always an error to use the class type as if it
689 is a \emph{complete type}, e.g., to declare objects or arrays of the class
690 type, or to enquire about its size or alignment requirements.
691
692 Instance layouts may be declared as objects with automatic storage duration
693 (colloquially, `allocated on the stack') or allocated dynamically, e.g.,
694 using @|malloc|.  They may be included as members of structures or unions, or
695 elements of arrays.  Sod's runtime system doesn't retain addresses of
696 instances, so, for example, Sod doesn't make using fancy allocators which
697 sometimes move objects around in memory any more difficult than it needs to
698 be.
699
700 There isn't any way to discover the alignment required for a particular
701 class's instances at runtime; it's best to be conservative and assume that
702 the platform's strictest alignment requirement applies.
703
704 The following simple function correctly allocates and returns space for an
705 instance of a class given a pointer to its class object @<cls>.
706 \begin{prog}
707   void *allocate_instance(const SodClass *cls)                  \\ \ind
708     \{ return malloc(cls@->cls.initsz); \}
709 \end{prog}
710
711 \subsubsection{Imprinting}
712 Once storage has been allocated, it must be \emph{imprinted} before it can be
713 used as an instance of a class, e.g., before any messages can be sent to it.
714
715 Imprinting an instance stores some metadata about its direct class in the
716 instance structure, so that the rest of the program (and Sod's runtime
717 library) can tell what sort of object it is, and how to use it.\footnote{%
718   Specifically, imprinting an instance's storage involves storing the
719   appropriate vtable pointers in the right places in it.} %
720 A class object's @|imprint| slot points to a function which will correctly
721 imprint storage for one of that class's instances.
722
723 Once an instance's storage has been imprinted, it is technically possible to
724 send messages to the instance; however the instance's slots are still
725 uninitialized at this point, the applicable methods are unlikely to do much
726 of any use unless they've been written specifically for the purpose.
727
728 The following simple function imprints storage at address @<p> as an instance
729 of a class, given a pointer to its class object @<cls>.
730 \begin{prog}
731   void imprint_instance(const SodClass *cls, void *p)           \\ \ind
732     \{ cls@->cls.imprint(p); \}
733 \end{prog}
734
735 \subsubsection{Initialization}
736 The final step for constructing a new instance is to \emph{initialize} it, to
737 establish the necessary invariants for the instance itself and the
738 environment in which it operates.
739
740 Details of initialization are necessarily class-specific, but typically it
741 involves setting the instance's slots to appropriate values, and possibly
742 linking it into some larger data structure to keep track of it.
743
744 Initialization is performed by sending the imprinted instance an @|init|
745 message, defined by the @|SodObject| class.  This message uses a nonstandard
746 method combination which works like the standard combination, except that the
747 \emph{default behaviour}, if there is no overriding method, is to initialize
748 the instance's slots, as described below, and to invoke each superclass's
749 initialization fragments.  This default behaviour may be invoked multiple
750 times if some method calls on its @|next_method| more than once, unless some
751 other method takes steps to prevent this.
752
753 Slots are initialized in a well-defined order.
754 \begin{itemize}
755 \item Slots defined by a more specific superclasses are initialized after
756   slots defined by a less specific superclass.
757 \item Slots defined by the same class are initialized in the order in which
758   their definitions appear.
759 \end{itemize}
760
761 A class can define \emph{initialization fragments}: pieces of literal code to
762 be executed to set up a new instance.  Each superclass's initialization
763 fragments are executed with @|me| bound to an instance pointer of the
764 appropriate superclass type, immediately after that superclass's slots (if
765 any) have been initialized; therefore, fragments defined by a more specific
766 superclass are executed after fragments defined by a more specific
767 superclass.  A class may define more than one initialization fragment: the
768 fragments are executed in the order in which they appear in the class
769 definition.  It is possible for an initialization fragment to use @|return|
770 or @|goto| for special control-flow effects, but this is not likely to be a
771 good idea.
772
773 The @|init| message accepts keyword arguments
774 (\xref{sec:concepts.methods.keywords}).  The set of acceptable keywords is
775 determined by the applicable methods as usual, but also by the
776 \emph{initargs} defined by the receiving instance's class and its
777 superclasses, which are made available to slot initializers and
778 initialization fragments.
779
780 There are two kinds of initarg definitions.  \emph{User initargs} are defined
781 by an explicit @|initarg| item appearing in a class definition: the item
782 defines a name, type, and (optionally) a default value for the initarg.
783 \emph{Slot initargs} are defined by attaching an @|initarg| property to a
784 slot or slot initializer item: the property's determines the initarg's name,
785 while the type is taken from the underlying slot type; slot initargs do not
786 have default values.  Both kinds define a \emph{direct initarg} for the
787 containing class.
788
789 Initargs are inherited.  The \emph{applicable} direct initargs for an @|init|
790 effective method are those defined by the receiving object's class, and all
791 of its superclasses.  Applicable direct initargs with the same name are
792 merged to form \emph{effective initargs}.  An error is reported if two
793 applicable direct initargs have the same name but different types.  The
794 default value of an effective initarg is taken from the most specific
795 applicable direct initarg which specifies a defalt value; if no applicable
796 direct initarg specifies a default value then the effective initarg has no
797 default.
798
799 All initarg values are made available at runtime to user code --
800 initialization fragments and slot initializer expressions -- through local
801 variables and a @|suppliedp| structure, as in a direct method
802 (\xref{sec:concepts.methods.keywords}).  Furthermore, slot initarg
803 definitions influence the initialization of slots.
804
805 The process for deciding how to initialize a particular slot works as
806 follows.
807 \begin{enumerate}
808 \item If there are any slot initargs defined on the slot, or any of its slot
809   initializers, \emph{and} the sender supplied a value for one or more of the
810   corresponding effective initargs, then the value of the most specific slot
811   initarg is stored in the slot.
812 \item Otherwise, if there are any slot initializers defined which include an
813   initializer expression, then the initializer expression from the most
814   specific such slot initializer is evaluated and its value stored in the
815   slot.
816 \item Otherwise, the slot is left uninitialized.
817 \end{enumerate}
818 Note that the default values (if any) of effective initargs do \emph{not}
819 affect this procedure.
820
821
822 \subsection{Destruction}
823 \label{sec:concepts.lifecycle.death}
824
825 Destruction of an instance, when it is no longer required, consists of two
826 steps.
827 \begin{enumerate}
828 \item \emph{Teardown} releases any resources held by the instance and
829   disentangles it from any external data structures.
830 \item \emph{Deallocation} releases the memory used to store the instance so
831   that it can be reused.
832 \end{enumerate}
833 Teardown alone, for objects which require special deallocation, or for which
834 deallocation occurs automatically (e.g., instances with automatic storage
835 duration, or instances whose storage will be garbage-collected), is performed
836 using the \descref{sod_teardown}[function]{fun}.  Destruction of instances
837 allocated from the standard @|malloc| heap is done using the
838 \descref{sod_destroy}[function]{fun}.
839
840 \subsubsection{Teardown}
841 Details of initialization are necessarily class-specific, but typically it
842 involves setting the instance's slots to appropriate values, and possibly
843 linking it into some larger data structure to keep track of it.
844
845 Teardown is performed by sending the instance the @|teardown| message,
846 defined by the @|SodObject| class.  The message returns an integer, used as a
847 boolean flag.  If the message returns zero, then the instance's storage
848 should be deallocated.  If the message returns nonzero, then it is safe for
849 the caller to forget about instance, but should not deallocate its storage.
850 This is \emph{not} an error return: if some teardown method fails then the
851 program may be in an inconsistent state and should not continue.
852
853 This simple protocol can be used, for example, to implement a reference
854 counting system, as follows.
855 \begin{prog}
856   [nick = ref]                                                  \\
857   class ReferenceCountedObject \{                               \\ \ind
858     unsigned nref = 1;                                          \\-
859     void inc() \{ me@->ref.nref++; \}                           \\-
860     [role = around]                                             \\
861     int obj.teardown()                                          \\
862     \{                                                          \\ \ind
863       if (--\,--me@->ref.nref) return (1);                      \\
864       else return (CALL_NEXT_METHOD);                         \-\\
865     \}                                                        \-\\
866   \}
867 \end{prog}
868
869 This message uses a nonstandard method combination which works like the
870 standard combination, except that the \emph{default behaviour}, if there is
871 no overriding method, is to execute the superclass's teardown fragments, and
872 to return zero.  This default behaviour may be invoked multiple times if some
873 method calls on its @|next_method| more than once, unless some other method
874 takes steps to prevent this.
875
876 A class can define \emph{teardown fragments}: pieces of literal code to be
877 executed to shut down an instance.  Each superclass's teardown fragments are
878 executed with @|me| bound to an instance pointer of the appropriate
879 superclass type; fragments defined by a more specific superclass are executed
880 before fragments defined by a more specific superclass.  A class may define
881 more than one teardown fragment: the fragments are executed in the order in
882 which they appear in the class definition.  It is possible for an
883 initialization fragment to use @|return| or @|goto| for special control-flow
884 effects, but this is not likely to be a good idea.  Similarly, it's probably
885 a better idea to use an @|around| method to influence the return value than
886 to write an explicit @|return| statement in a teardown fragment.
887
888 \subsubsection{Deallocation}
889 The details of instance deallocation are obviously specific to the allocation
890 strategy used by the instance, and this is often orthogonal from the object's
891 class.
892
893 The code which makes the decision to destroy an object may often not be aware
894 of the object's direct class.  Low-level details of deallocation often
895 require the proper base address of the instance's storage, which can be
896 determined using the \descref{SOD_INSTBASE}[macro]{mac}.
897
898 %%%--------------------------------------------------------------------------
899 \section{Metaclasses} \label{sec:concepts.metaclasses}
900
901 %%%----- That's all, folks --------------------------------------------------
902
903 %%% Local variables:
904 %%% mode: LaTeX
905 %%% TeX-master: "sod.tex"
906 %%% TeX-PDF-mode: t
907 %%% End: