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