lib/keyword.3: Missing word.
[sod] / doc / concepts.tex
CommitLineData
1f7d590d
MW
1%%% -*-latex-*-
2%%%
3%%% Conceptual background
4%%%
5%%% (c) 2015 Straylight/Edgeware
6%%%
7
8%%%----- Licensing notice ---------------------------------------------------
9%%%
e0808c47 10%%% This file is part of the Sensible Object Design, an object system for C.
1f7d590d
MW
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
3cc520db 26\chapter{Concepts} \label{ch:concepts}
1f7d590d 27
3cc520db 28%%%--------------------------------------------------------------------------
3cc520db
MW
29\section{Modules} \label{sec:concepts.modules}
30
31A \emph{module} is the top-level syntactic unit of input to the Sod
32translator. As described above, given an input module, the translator
33generates C source and header files.
34
35A module can \emph{import} other modules. This makes the type names and
36classes defined in those other modules available to class definitions in the
37importing module. Sod's module system is intentionally very simple. There
38are no private declarations or attempts to hide things.
39
40As well as importing existing modules, a module can include a number of
41different 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}
54Each 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
57information to module items, so extensions can make use of them without
58having to implement additional syntax.
59
60%%%--------------------------------------------------------------------------
61\section{Classes, instances, and slots} \label{sec:concepts.classes}
62
63For the most part, Sod takes a fairly traditional view of what it means to be
64an object system.
65
46fe5a33
MW
66An \emph{object} maintains \emph{state} and exhibits \emph{behaviour}.
67(Here, we're using the term `object' in the usual sense of `object-oriented
68programming', rather than that of the ISO~C standard. Once we have defined
69an `instance' below, we shall generally prefer that term, so as to prevent
70further confusion between these two uses of the word.)
71
72An object's state is maintained in named \emph{slots}, each of which can
73store a C value of an appropriate (scalar or aggregate) type. An object's
74behaviour is stimulated by sending it \emph{messages}. A message has a name,
75and may carry a number of arguments, which are C values; sending a message
76may result in the state of receiving object (or other objects) being changed,
77and a C value being returned to the sender.
78
79Every object is a \emph{direct instance} of exactly one \emph{class}. The
80class determines which slots its instances have, which messages its instances
81can be sent, and which methods are invoked when those messages are received.
82The Sod translator's main job is to read class definitions and convert them
83into appropriate C declarations, tables, and functions. An object cannot
3cc520db
MW
84(usually) change its direct class, and the direct class of an object is not
85affected by, for example, the static type of a pointer to it.
86
46fe5a33
MW
87If an object~$x$ is a direct instance of some class~$C$, then we say that $C$
88is \emph{the class of}~$x$. Note that the class of an object is a property
89of the object's value at runtime, and not of C's compile-time type system.
90We shall be careful in distinguishing C's compile-time notion of \emph{type}
91from Sod's run-time notion of \emph{class}.
92
0a2d4b68 93
3cc520db
MW
94\subsection{Superclasses and inheritance}
95\label{sec:concepts.classes.inherit}
96
97\subsubsection{Class relationships}
98Each class has zero or more \emph{direct superclasses}.
99
100A class with no direct superclasses is called a \emph{root class}. The Sod
101runtime library includes a root class named @|SodObject|; making new root
102classes is somewhat tricky, and won't be discussed further here.
103
104Classes can have more than one direct superclass, i.e., Sod supports
105\emph{multiple inheritance}. A Sod class definition for a class~$C$ lists
106the direct superclasses of $C$ in a particular order. This order is called
107the \emph{local precedence order} of $C$, and the list which consists of $C$
108follows by $C$'s direct superclasses in local precedence order is called the
109$C$'s \emph{local precedence list}.
110
111The multiple inheritance in Sod works similarly to multiple inheritance in
112Lisp-like languages, such as Common Lisp, EuLisp, Dylan, and Python, which is
113very different from how multiple inheritance works in \Cplusplus.\footnote{%
114 The latter can be summarized as `badly'. By default in \Cplusplus, an
115 instance receives an additional copy of superclass's state for each path
116 through the class graph from the instance's direct class to that
117 superclass, though this behaviour can be overridden by declaring
118 superclasses to be @|virtual|. Also, \Cplusplus\ offers only trivial
119 method combination (\xref{sec:concepts.methods}), leaving programmers to
120 deal with delegation manually and (usually) statically.} %
121
122If $C$ is a class, then the \emph{superclasses} of $C$ are
123\begin{itemize}
124\item $C$ itself, and
125\item the superclasses of each of $C$'s direct superclasses.
126\end{itemize}
127The \emph{proper superclasses} of a class $C$ are the superclasses of $C$
128except for $C$ itself. If a class $B$ is a (direct, proper) superclass of
129$C$, then $C$ is a \emph{(direct, proper) subclass} of $B$. If $C$ is a root
130class then the only superclass of $C$ is $C$ itself, and $C$ has no proper
131superclasses.
132
133If an object is a direct instance of class~$C$ then the object is also an
46fe5a33 134(indirect) \emph{instance} of every superclass of $C$.
3cc520db 135
054e8f8f 136If $C$ has a proper superclass $B$, then $B$ must not have $C$ as a direct
e8fd6aea
MW
137superclass. In different terms, if we construct a directed graph, whose
138nodes are classes, and draw an arc from each class to each of its direct
139superclasses, then this graph must be acyclic. In yet other terms, the `is a
140superclass of' relation is a partial order on classes.
3cc520db
MW
141
142\subsubsection{The class precedence list}
143This partial order is not quite sufficient for our purposes. For each class
144$C$, we shall need to extend it into a total order on $C$'s superclasses.
145This calculation is called \emph{superclass linearization}, and the result is
146a \emph{class precedence list}, which lists each of $C$'s superclasses
147exactly once. If a superclass $B$ precedes (resp.\ follows) some other
148superclass $A$ in $C$'s class precedence list, then we say that $B$ is a more
149(resp.\ less) \emph{specific} superclass of $C$ than $A$ is.
150
151The superclass linearization algorithm isn't fixed, and extensions to the
152translator can introduce new linearizations for special effects, but the
153following properties are expected to hold.
154\begin{itemize}
155\item The first class in $C$'s class precedence list is $C$ itself; i.e.,
156 $C$ is always its own most specific superclass.
157\item If $A$ and $B$ are both superclasses of $C$, and $A$ is a proper
158 superclass of $B$ then $A$ appears after $B$ in $C$'s class precedence
159 list, i.e., $B$ is a more specific superclass of $C$ than $A$ is.
160\end{itemize}
161The default linearization algorithm used in Sod is the \emph{C3} algorithm,
9cd5cf15 162which has a number of good properties described in~\cite{Barrett:1996:MSL}.
3cc520db
MW
163It works as follows.
164\begin{itemize}
165\item A \emph{merge} of some number of input lists is a single list
166 containing each item that is in any of the input lists exactly once, and no
167 other items; if an item $x$ appears before an item $y$ in any input list,
168 then $x$ also appears before $y$ in the merge. If a collection of lists
169 have no merge then they are said to be \emph{inconsistent}.
170\item The class precedence list of a class $C$ is a merge of the local
171 precedence list of $C$ together with the class precedence lists of each of
172 $C$'s direct superclasses.
173\item If there are no such merges, then the definition of $C$ is invalid.
174\item Suppose that there are multiple candidate merges. Consider the
175 earliest position in these candidate merges at which they disagree. The
176 \emph{candidate classes} at this position are the classes appearing at this
177 position in the candidate merges. Each candidate class must be a
781a8fbd 178 superclass of distinct direct superclasses of $C$, since otherwise the
3cc520db
MW
179 candidates would be ordered by their common subclass's class precedence
180 list. The class precedence list contains, at this position, that candidate
181 class whose subclass appears earliest in $C$'s local precedence order.
182\end{itemize}
183
4075ab40
MW
184\begin{figure}
185 \centering
186 \begin{tikzpicture}[x=7.5mm, y=-14mm, baseline=(current bounding box.east)]
187 \node[lit] at ( 0, 0) (R) {SodObject};
188 \node[lit] at (-3, +1) (A) {A}; \draw[->] (A) -- (R);
189 \node[lit] at (-1, +1) (B) {B}; \draw[->] (B) -- (R);
190 \node[lit] at (+1, +1) (C) {C}; \draw[->] (C) -- (R);
191 \node[lit] at (+3, +1) (D) {D}; \draw[->] (D) -- (R);
192 \node[lit] at (-2, +2) (E) {E}; \draw[->] (E) -- (A);
193 \draw[->] (E) -- (B);
194 \node[lit] at (+2, +2) (F) {F}; \draw[->] (F) -- (A);
195 \draw[->] (F) -- (D);
196 \node[lit] at (-1, +3) (G) {G}; \draw[->] (G) -- (E);
197 \draw[->] (G) -- (C);
198 \node[lit] at (+1, +3) (H) {H}; \draw[->] (H) -- (F);
199 \node[lit] at ( 0, +4) (I) {I}; \draw[->] (I) -- (G);
200 \draw[->] (I) -- (H);
201 \end{tikzpicture}
202 \quad
203 \vrule
204 \quad
205 \begin{minipage}[c]{0.45\hsize}
206 \begin{nprog}
207 class A: SodObject \{ \}\quad\=@/* @|A|, @|SodObject| */ \\
208 class B: SodObject \{ \}\>@/* @|B|, @|SodObject| */ \\
209 class C: SodObject \{ \}\>@/* @|B|, @|SodObject| */ \\
210 class D: SodObject \{ \}\>@/* @|B|, @|SodObject| */ \\+
211 class E: A, B \{ \}\quad\=@/* @|E|, @|A|, @|B|, \dots */ \\
212 class F: A, D \{ \}\>@/* @|F|, @|A|, @|D|, \dots */ \\+
213 class G: E, C \{ \}\>@/* @|G|, @|E|, @|A|,
214 @|B|, @|C|, \dots */ \\
215 class H: F \{ \}\>@/* @|H|, @|F|, @|A|, @|D|, \dots */ \\+
216 class I: G, H \{ \}\>@/* @|I|, @|G|, @|E|, @|H|, @|F|,
217 @|A|, @|B|, @|C|, @|D|, \dots */
218 \end{nprog}
219 \end{minipage}
220
221 \caption{An example class graph and class precedence lists}
222 \label{fig:concepts.classes.cpl-example}
223\end{figure}
224
225\begin{example}
226 Consider the class relationships shown in
227 \xref{fig:concepts.classes.cpl-example}.
228
229 \begin{itemize}
230
231 \item @|SodObject| has no proper superclasses. Its class precedence list
232 is therefore simply $\langle @|SodObject| \rangle$.
233
234 \item In general, if $X$ is a direct subclass only of $Y$, and $Y$'s class
235 precedence list is $\langle Y, \ldots \rangle$, then $X$'s class
236 precedence list is $\langle X, Y, \ldots \rangle$. This explains $A$,
237 $B$, $C$, $D$, and $H$.
238
239 \item $E$'s list is found by merging its local precedence list $\langle E,
240 A, B \rangle$ with the class precedence lists of its direct superclasses,
241 which are $\langle A, @|SodObject| \rangle$ and $\langle B, @|SodObject|
242 \rangle$. Clearly, @|SodObject| must be last, and $E$'s local precedence
243 list orders the rest, giving $\langle E, A, B, @|SodObject|, \rangle$.
244 $F$ is similar.
245
246 \item We determine $G$'s class precedence list by merging the three lists
247 $\langle G, E, C \rangle$, $\langle E, A, B, @|SodObject| \rangle$, and
248 $\langle C, @|SodObject| \rangle$. The class precedence list begins
249 $\langle G, E, \ldots \rangle$, but the individual lists don't order $A$
250 and $C$. Comparing these to $G$'s direct superclasses, we see that $A$
54cf3a30
MW
251 is a superclass of $E$, while $C$ is a superclass of -- indeed equal to
252 -- $C$; so $A$ must precede $C$, as must $B$, and the final list is
253 $\langle G, E, A, B, C, @|SodObject| \rangle$.
4075ab40
MW
254
255 \item Finally, we determine $I$'s class precedence list by merging $\langle
256 I, G, H \rangle$, $\langle G, E, A, B, C, @|SodObject| \rangle$, and
257 $\langle H, F, A, D, @|SodObject| \rangle$. The list begins $\langle I,
258 G, \ldots \rangle$, and then we must break a tie between $E$ and $H$; but
54cf3a30 259 $E$ is a superclass of $G$, so $E$ wins. Next, $H$ and $F$ must precede
4075ab40
MW
260 $A$, since these are ordered by $H$'s class precedence list. Then $B$
261 and $C$ precede $D$, since the former are superclasses of $G$, and the
262 final list is $\langle I, G, E, H, F, A, B, C, D, @|SodObject| \rangle$.
263
264 \end{itemize}
265
266 (This example combines elements from \cite{Barrett:1996:MSL} and
267 \cite{Ducournau:1994:PMM}.)
268\end{example}
269
3cc520db
MW
270\subsubsection{Class links and chains}
271The definition for a class $C$ may distinguish one of its proper superclasses
272as being the \emph{link superclass} for class $C$. Not every class need have
273a link superclass, and the link superclass of a class $C$, if it exists, need
274not be a direct superclass of $C$.
275
276Superclass links must obey the following rule: if $C$ is a class, then there
756e9293
MW
277must be no three distinct superclasses $X$, $Y$ and~$Z$ of $C$ such that $Z$
278is the link superclass of both $X$ and $Y$. As a consequence of this rule,
279the superclasses of $C$ can be partitioned into linear \emph{chains}, such
280that superclasses $A$ and $B$ are in the same chain if and only if one can
281trace a path from $A$ to $B$ by following superclass links, or \emph{vice
282versa}.
3cc520db
MW
283
284Since a class links only to one of its proper superclasses, the classes in a
285chain are naturally ordered from most- to least-specific. The least specific
286class in a chain is called the \emph{chain head}; the most specific class is
287the \emph{chain tail}. Chains are often named after their chain head
288classes.
289
c6c9615b 290
3cc520db
MW
291\subsection{Names}
292\label{sec:concepts.classes.names}
293
294Classes have a number of other attributes:
295\begin{itemize}
296\item A \emph{name}, which is a C identifier. Class names must be globally
297 unique. The class name is used in the names of a number of associated
298 definitions, to be described later.
299\item A \emph{nickname}, which is also a C identifier. Unlike names,
300 nicknames are not required to be globally unique. If $C$ is any class,
301 then all the superclasses of $C$ must have distinct nicknames.
302\end{itemize}
303
0a2d4b68 304
3cc520db
MW
305\subsection{Slots} \label{sec:concepts.classes.slots}
306
307Each class defines a number of \emph{slots}. Much like a structure member, a
308slot has a \emph{name}, which is a C identifier, and a \emph{type}. Unlike
309many other object systems, different superclasses of a class $C$ can define
310slots with the same name without ambiguity, since slot references are always
311qualified by the defining class's nickname.
312
313\subsubsection{Slot initializers}
314As well as defining slot names and types, a class can also associate an
315\emph{initial value} with each slot defined by itself or one of its
98da9322 316subclasses. A class $C$ provides an \emph{initialization message} (see
d24d47f5 317\xref{sec:concepts.lifecycle.birth}, and \xref{sec:structures.root.sodclass})
98da9322
MW
318whose methods set the slots of a \emph{direct} instance of the class to the
319correct initial values. If several of $C$'s superclasses define initializers
320for the same slot then the initializer from the most specific such class is
321used. If none of $C$'s superclasses define an initializer for some slot then
322that slot will be left uninitialized.
3cc520db
MW
323
324The initializer for a slot with scalar type may be any C expression. The
325initializer for a slot with aggregate type must contain only constant
326expressions if the generated code is expected to be processed by a
327implementation of C89. Initializers will be evaluated once each time an
328instance is initialized.
329
27ec3825
MW
330Slots are initialized in reverse-precedence order of their defining classes;
331i.e., slots defined by a less specific superclass are initialized earlier
332than slots defined by a more specific superclass. Slots defined by the same
333class are initialized in the order in which they appear in the class
334definition.
335
336The initializer for a slot may refer to other slots in the same object, via
337the @|me| pointer: in an initializer for a slot defined by a class $C$, @|me|
338has type `pointer to $C$'. (Note that the type of @|me| depends only on the
339class which defined the slot, not the class which defined the initializer.)
340
997b4d2b
MW
341A class can also define \emph{class slot initializers}, which provide values
342for a slot defined by its metaclass; see \xref{sec:concepts.metaclasses} for
343details.
344
0a2d4b68 345
3cc520db
MW
346\subsection{C language integration} \label{sec:concepts.classes.c}
347
c06ba266
MW
348It is very important to distinguish compile-time C \emph{types} from Sod's
349run-time \emph{classes}: see \xref{sec:concepts.classes}.
350
3cc520db
MW
351For each class~$C$, the Sod translator defines a C type, the \emph{class
352type}, with the same name. This is the usual type used when considering an
353object as an instance of class~$C$. No entire object will normally have a
354class type,\footnote{%
355 In general, a class type only captures the structure of one of the
356 superclass chains of an instance. A full instance layout contains multiple
357 chains. See \xref{sec:structures.layout} for the full details.} %
358so access to instances is almost always via pointers.
359
c06ba266
MW
360Usually, a value of type pointer-to-class-type of class~$C$ will point into
361an instance of class $C$. However, clever (or foolish) use of pointer
362conversions can invalidate this relationship.
363
3cc520db
MW
364\subsubsection{Access to slots}
365The class type for a class~$C$ is actually a structure. It contains one
366member for each class in $C$'s superclass chain, named with that class's
367nickname. Each of these members is also a structure, containing the
368corresponding class's slots, one member per slot. There's nothing special
369about these slot members: C code can access them in the usual way.
370
f2309139
MW
371For example, given the definition
372\begin{prog}
373 [nick = mine] \\
374 class MyClass: SodObject \{ \\ \ind
375 int x; \-\\
376 \}
377\end{prog}
378the simple function
3cc520db 379\begin{prog}
c18d6aba 380 int get_x(MyClass *m) \{ return (m@->mine.x); \}
3cc520db
MW
381\end{prog}
382will extract the value of @|x| from an instance of @|MyClass|.
383
384All of this means that there's no such thing as `private' or `protected'
385slots. If you want to hide implementation details, the best approach is to
386stash them in a dynamically allocated private structure, and leave a pointer
387to it in a slot. (This will also help preserve binary compatibility, because
388the private structure can grow more members as needed. See
021d9f84 389\xref{sec:concepts.compatibility} for more details.)
3cc520db 390
4b4aec4e
MW
391Slots defined by $C$'s link superclass, or any other superclass in the same
392chain, can be accessed in the same way. Slots defined by other superclasses
393can't be accessed directly: the instance pointer must be \emph{converted} to
394point to a different chain. See the subsection `Conversions' below.
395
ff06eeb1 396
f4e44f7f
MW
397\subsubsection{Sending messages}
398Sod defines a macro for each message. If a class $C$ defines a message $m$,
399then the macro is called @|$C$_$m$|. The macro takes a pointer to the
400receiving object as its first argument, followed by the message arguments, if
401any, and returns the value returned by the object's effective method for the
402message (if any). If you have a pointer to an instance of any of $C$'s
403subclasses, then you can send it the message; it doesn't matter whether the
404subclass is on the same chain. Note that the receiver argument is evaluated
405twice, so it's not safe to write a receiver expression which has
406side-effects.
407
408For example, suppose we defined
409\begin{prog}
410 [nick = soupy] \\
411 class Super: SodObject \{ \\ \ind
412 void msg(const char *m); \-\\
413 \} \\+
414 class Sub: Super \{ \\ \ind
415 void soupy.msg(const char *m)
416 \{ printf("sub sent `\%s'@\\n", m); \} \-\\
417 \}
418\end{prog}
419then we can send the message like this:
420\begin{prog}
421 Sub *sub = /* \dots\ */; \\
422 Super_msg(sub, "hello");
423\end{prog}
424
425What happens under the covers is as follows. The structure pointed to by the
426instance pointer has a member named @|_vt|, which points to a structure
427called a `virtual table', or \emph{vtable}, which contains various pieces of
428information about the object's direct class and layout, and holds pointers to
429method entries for the messages which the object can receive. The
430message-sending macro in the example above expands to something similar to
431\begin{prog}
432 sub@->_vt.sub.msg(sub, "Hello");
433\end{prog}
434
435The vtable contains other useful information, such as a pointer to the
436instance's direct class's \emph{class object} (described below). The full
437details of the contents and layout of vtables are given in
438\xref{sec:structures.layout.vtable}.
caa6f4b9
MW
439
440
3cc520db
MW
441\subsubsection{Class objects}
442In Sod's object system, classes are objects too. Therefore classes are
443themselves instances; the class of a class is called a \emph{metaclass}. The
444consequences of this are explored in \xref{sec:concepts.metaclasses}. The
445\emph{class object} has the same name as the class, suffixed with
446`@|__class|'\footnote{%
447 This is not quite true. @|$C$__class| is actually a macro. See
448 \xref{sec:structures.layout.additional} for the gory details.} %
449and its type is usually @|SodClass|; @|SodClass|'s nickname is @|cls|.
450
451A class object's slots contain or point to useful information, tables and
452functions for working with that class's instances. (The @|SodClass| class
054e8f8f
MW
453doesn't define any messages, so it doesn't have any methods other than for
454the @|SodObject| lifecycle messages @|init| and @|teardown|; see
455\xref{sec:concepts.lifecycle}. In Sod, a class slot containing a function
456pointer is not at all the same thing as a method.)
3cc520db 457
3cc520db 458\subsubsection{Conversions}
e4ea29d8
MW
459Suppose one has a value of type pointer-to-class-type for some class~$C$, and
460wants to convert it to a pointer-to-class-type for some other class~$B$.
3cc520db
MW
461There are three main cases to distinguish.
462\begin{itemize}
463\item If $B$ is a superclass of~$C$, in the same chain, then the conversion
464 is an \emph{in-chain upcast}. The conversion can be performed using the
465 appropriate generated upcast macro (see below), or by simply casting the
466 pointer, using C's usual cast operator (or the \Cplusplus\ @|static_cast<>|
467 operator).
468\item If $B$ is a superclass of~$C$, in a different chain, then the
469 conversion is a \emph{cross-chain upcast}. The conversion is more than a
470 simple type change: the pointer value must be adjusted. If the direct
471 class of the instance in question is not known, the conversion will require
472 a lookup at runtime to find the appropriate offset by which to adjust the
473 pointer. The conversion can be performed using the appropriate generated
474 upcast macro (see below); the general case is handled by the macro
58f9b400 475 \descref{SOD_XCHAIN}{mac}.
e4ea29d8 476\item If $B$ is a subclass of~$C$ then the conversion is a \emph{downcast};
3cc520db
MW
477 otherwise the conversion is a~\emph{cross-cast}. In either case, the
478 conversion can fail: the object in question might not be an instance of~$B$
e4ea29d8 479 after all. The macro \descref{SOD_CONVERT}{mac} and the function
58f9b400 480 \descref{sod_convert}{fun} perform general conversions. They return a null
054e8f8f 481 pointer if the conversion fails. (These are therefore your analogue to the
e4ea29d8 482 \Cplusplus\ @|dynamic_cast<>| operator.)
3cc520db
MW
483\end{itemize}
484The Sod translator generates macros for performing both in-chain and
485cross-chain upcasts. For each class~$C$, and each proper superclass~$B$
486of~$C$, a macro is defined: given an argument of type pointer to class type
487of~$C$, it returns a pointer to the same instance, only with type pointer to
488class type of~$B$, adjusted as necessary in the case of a cross-chain
489conversion. The macro is named by concatenating
490\begin{itemize}
491\item the name of class~$C$, in upper case,
492\item the characters `@|__CONV_|', and
493\item the nickname of class~$B$, in upper case;
494\end{itemize}
495e.g., if $C$ is named @|MyClass|, and $B$'s name is @|SuperClass| with
496nickname @|super|, then the macro @|MYCLASS__CONV_SUPER| converts a
497@|MyClass~*| to a @|SuperClass~*|. See
498\xref{sec:structures.layout.additional} for the formal description.
499
500%%%--------------------------------------------------------------------------
9e91c8e7
MW
501\section{Keyword arguments} \label{sec:concepts.keywords}
502
503In standard C, the actual arguments provided to a function are matched up
504with the formal arguments given in the function definition according to their
505ordering in a list. Unless the (rather cumbersome) machinery for dealing
506with variable-length argument tails (@|<stdarg.h>|) is used, exactly the
507correct number of arguments must be supplied, and in the correct order.
508
509A \emph{keyword argument} is matched by its distinctive \emph{name}, rather
510than by its position in a list. Keyword arguments may be \emph{omitted},
511causing some default behaviour by the function. A function can detect
512whether a particular keyword argument was supplied: so the default behaviour
513need not be the same as that caused by any specific value of the argument.
514
515Keyword arguments can be provided in three ways.
516\begin{enumerate}
517\item Directly, as a variable-length argument tail, consisting (for the most
518 part) of alternating keyword names, as pointers to null-terminated strings,
519 and argument values, and terminated by a null pointer. This is somewhat
520 error-prone, and the support library defines some macros which help ensure
521 that keyword argument lists are well formed.
522\item Indirectly, through a @|va_list| object capturing a variable-length
523 argument tail passed to some other function. Such indirect argument tails
524 have the same structure as the direct argument tails described above.
525 Because @|va_list| objects are hard to copy, the keyword-argument support
526 library consistently passes @|va_list| objects \emph{by reference}
527 throughout its programming interface.
528\item Indirectly, through a vector of @|struct kwval| objects, each of which
529 contains a keyword name, as a pointer to a null-terminated string, and the
530 \emph{address} of a corresponding argument value. (This indirection is
531 necessary so that the items in the vector can be of uniform size.)
532 Argument vectors are rather inconvenient to use, but are the only practical
533 way in which a caller can decide at runtime which arguments to include in a
534 call, which is useful when writing wrapper functions.
535\end{enumerate}
536
537Keyword arguments are provided as a general feature for C functions.
43073476 538However, Sod has special support for messages which accept keyword arguments
8ec911fa 539(\xref{sec:concepts.methods.keywords}); and they play an essential rôle in
a142609c 540the instance construction protocol (\xref{sec:concepts.lifecycle.birth}).
9e91c8e7
MW
541
542%%%--------------------------------------------------------------------------
3cc520db
MW
543\section{Messages and methods} \label{sec:concepts.methods}
544
545Objects can be sent \emph{messages}. A message has a \emph{name}, and
546carries a number of \emph{arguments}. When an object is sent a message, a
547function, determined by the receiving object's class, is invoked, passing it
548the receiver and the message arguments. This function is called the
549class's \emph{effective method} for the message. The effective method can do
550anything a C function can do, including reading or updating program state or
551object slots, sending more messages, calling other functions, issuing system
552calls, or performing I/O; if it finishes, it may return a value, which is
553returned in turn to the message sender.
554
555The set of messages an object can receive, characterized by their names,
556argument types, and return type, is determined by the object's class. Each
557class can define new messages, which can be received by any instance of that
558class. The messages defined by a single class must have distinct names:
559there is no `function overloading'. As with slots
560(\xref{sec:concepts.classes.slots}), messages defined by distinct classes are
561always distinct, even if they have the same names: references to messages are
562always qualified by the defining class's name or nickname.
563
564Messages may take any number of arguments, of any non-array value type.
565Since message sends are effectively function calls, arguments of array type
566are implicitly converted to values of the corresponding pointer type. While
567message definitions may ascribe an array type to an argument, the formal
568argument will have pointer type, as is usual for C functions. A message may
569accept a variable-length argument suffix, denoted @|\dots|.
570
571A class definition may include \emph{direct methods} for messages defined by
572it or any of its superclasses.
573
574Like messages, direct methods define argument lists and return types, but
8ec911fa 575they may also have a \emph{body}, and a \emph{rôle}.
3cc520db
MW
576
577A direct method need not have the same argument list or return type as its
578message. The acceptable argument lists and return types for a method depend
579on the message, in particular its method combination
8ec911fa 580(\xref{sec:concepts.methods.combination}), and the method's rôle.
3cc520db
MW
581
582A direct method body is a block of C code, and the Sod translator usually
583defines, for each direct method, a function with external linkage, whose body
584contains a copy of the direct method body. Within the body of a direct
585method defined for a class $C$, the variable @|me|, of type pointer to class
586type of $C$, refers to the receiving object.
587
0a2d4b68 588
3cc520db
MW
589\subsection{Effective methods and method combinations}
590\label{sec:concepts.methods.combination}
591
592For each message a direct instance of a class might receive, there is a set
593of \emph{applicable methods}, which are exactly the direct methods defined on
594the object's class and its superclasses. These direct methods are combined
595together to form the \emph{effective method} for that particular class and
596message. Direct methods can be combined into an effective method in
597different ways, according to the \emph{method combination} specified by the
8ec911fa
MW
598message. The method combination determines which direct method rôles are
599acceptable, and, for each rôle, the appropriate argument lists and return
3cc520db
MW
600types.
601
602One direct method, $M$, is said to be more (resp.\ less) \emph{specific} than
603another, $N$, with respect to a receiving class~$C$, if the class defining
604$M$ is a more (resp.\ less) specific superclass of~$C$ than the class
605defining $N$.
606
43073476 607\subsubsection{The standard method combination}
3cc520db
MW
608The default method combination is called the \emph{standard method
609combination}; other method combinations are useful occasionally for special
8ec911fa 610effects. The standard method combination accepts four direct method rôles,
9761db0d 611called `primary' (the default), @|before|, @|after|, and @|around|.
3cc520db
MW
612
613All direct methods subject to the standard method combination must have
614argument lists which \emph{match} the message's argument list:
615\begin{itemize}
616\item the method's arguments must have the same types as the message, though
617 the arguments may have different names; and
618\item if the message accepts a variable-length argument suffix then the
619 direct method must instead have a final argument of type @|va_list|.
620\end{itemize}
b1254eb6
MW
621Primary and @|around| methods must have the same return type as the message;
622@|before| and @|after| methods must return @|void| regardless of the
623message's return type.
3cc520db
MW
624
625If there are no applicable primary methods then no effective method is
626constructed: the vtables contain null pointers in place of pointers to method
627entry functions.
628
f1aa19a8 629\begin{figure}
d82d5db5 630 \hbox to\hsize{\hss\hbox{\begin{tikzpicture}
a4094071 631 [order/.append style={color=green!70!black},
f1aa19a8
MW
632 code/.append style={font=\sffamily},
633 action/.append style={font=\itshape},
634 method/.append style={rectangle, draw=black, thin, fill=blue!30,
635 text height=\ht\strutbox, text depth=\dp\strutbox,
636 minimum width=40mm}]
637
638 \def\delgstack#1#2#3{
639 \node (#10) [method, #2] {#3};
640 \node (#11) [method, above=6mm of #10] {#3};
641 \draw [->] ($(#10.north)!.5!(#10.north west) + (0mm, 1mm)$) --
642 ++(0mm, 4mm)
643 node [code, left=4pt, midway] {next_method};
644 \draw [<-] ($(#10.north)!.5!(#10.north east) + (0mm, 1mm)$) --
645 ++(0mm, 4mm)
646 node [action, right=4pt, midway] {return};
647 \draw [->] ($(#11.north)!.5!(#11.north west) + (0mm, 1mm)$) --
648 ++(0mm, 4mm)
649 node [code, left=4pt, midway] {next_method}
650 node (ld) [above] {$\smash\vdots\mathstrut$};
651 \draw [<-] ($(#11.north)!.5!(#11.north east) + (0mm, 1mm)$) --
652 ++(0mm, 4mm)
653 node [action, right=4pt, midway] {return}
654 node (rd) [above] {$\smash\vdots\mathstrut$};
655 \draw [->] ($(ld.north) + (0mm, 1mm)$) -- ++(0mm, 4mm)
656 node [code, left=4pt, midway] {next_method};
657 \draw [<-] ($(rd.north) + (0mm, 1mm)$) -- ++(0mm, 4mm)
658 node [action, right=4pt, midway] {return};
659 \node (p) at ($(ld.north)!.5!(rd.north)$) {};
660 \node (#1n) [method, above=5mm of p] {#3};
661 \draw [->, order] ($(#10.south east) + (4mm, 1mm)$) --
662 ($(#1n.north east) + (4mm, -1mm)$)
663 node [midway, right, align=left]
664 {Most to \\ least \\ specific};}
665
dc20d91f 666 \delgstack{a}{}{@|around| method}
f1aa19a8
MW
667 \draw [<-] ($(a0.south)!.5!(a0.south west) - (0mm, 1mm)$) --
668 ++(0mm, -4mm);
669 \draw [->] ($(a0.south)!.5!(a0.south east) - (0mm, 1mm)$) --
670 ++(0mm, -4mm)
671 node [action, right=4pt, midway] {return};
672
673 \draw [->] ($(an.north)!.6!(an.north west) + (0mm, 1mm)$) --
674 ++(-8mm, 8mm)
675 node [code, midway, left=3mm] {next_method}
676 node (b0) [method, above left = 1mm + 4mm and -6mm - 4mm] {};
677 \node (b1) [method] at ($(b0) - (2mm, 2mm)$) {};
dc20d91f 678 \node (bn) [method] at ($(b1) - (2mm, 2mm)$) {@|before| method};
f1aa19a8
MW
679 \draw [->, order] ($(bn.west) - (6mm, 0mm)$) -- ++(12mm, 12mm)
680 node [midway, above left, align=center] {Most to \\ least \\ specific};
681 \draw [->] ($(b0.north east) + (-10mm, 1mm)$) -- ++(8mm, 8mm)
682 node (p) {};
683
684 \delgstack{m}{above right=1mm and 0mm of an.west |- p}{Primary method}
685 \draw [->] ($(mn.north)!.5!(mn.north west) + (0mm, 1mm)$) -- ++(0mm, 4mm)
686 node [code, left=4pt, midway] {next_method}
687 node [above right = 0mm and -8mm]
688 {$\vcenter{\hbox{\Huge\textcolor{red}{!}}}
689 \vcenter{\hbox{\begin{tabular}[c]{l}
690 \textsf{next_method} \\
691 pointer is null
692 \end{tabular}}}$};
693
694 \draw [->, color=blue, dotted]
695 ($(m0.south)!.2!(m0.south east) - (0mm, 1mm)$) --
696 ($(an.north)!.2!(an.north east) + (0mm, 1mm)$)
697 node [midway, sloped, below] {Return value};
698
699 \draw [<-] ($(an.north)!.6!(an.north east) + (0mm, 1mm)$) --
700 ++(8mm, 8mm)
701 node [action, midway, right=3mm] {return}
702 node (f0) [method, above right = 1mm and -6mm] {};
703 \node (f1) [method] at ($(f0) + (-2mm, 2mm)$) {};
dc20d91f 704 \node (fn) [method] at ($(f1) + (-2mm, 2mm)$) {@|after| method};
f1aa19a8
MW
705 \draw [<-, order] ($(f0.east) + (6mm, 0mm)$) -- ++(-12mm, 12mm)
706 node [midway, above right, align=center]
707 {Least to \\ most \\ specific};
708 \draw [<-] ($(fn.north west) + (6mm, 1mm)$) -- ++(-8mm, 8mm);
709
d82d5db5 710 \end{tikzpicture}}\hss}
f1aa19a8
MW
711
712 \caption{The standard method combination}
713 \label{fig:concepts.methods.stdmeth}
714\end{figure}
715
3cc520db 716The effective method for a message with standard method combination works as
f1aa19a8 717follows (see also~\xref{fig:concepts.methods.stdmeth}).
3cc520db
MW
718\begin{enumerate}
719
8ec911fa 720\item If any applicable methods have the @|around| rôle, then the most
3cc520db
MW
721 specific such method, with respect to the class of the receiving object, is
722 invoked.
723
b1254eb6 724 Within the body of an @|around| method, the variable @|next_method| is
3cc520db
MW
725 defined, having pointer-to-function type. The method may call this
726 function, as described below, any number of times.
727
b1254eb6
MW
728 If there any remaining @|around| methods, then @|next_method| invokes the
729 next most specific such method, returning whichever value that method
dc20d91f
MW
730 returns; otherwise the behaviour of @|next_method| is to invoke the
731 @|before| methods (if any), followed by the most specific primary method,
b0563651 732 followed by the @|after| methods (if any), and to return whichever value
dc20d91f
MW
733 was returned by the most specific primary method, as described in the
734 following items. That is, the behaviour of the least specific @|around|
735 method's @|next_method| function is exactly the behaviour that the
736 effective method would have if there were no @|around| methods. Note that
737 if the least-specific @|around| method calls its @|next_method| more than
738 once then the whole sequence of @|before|, primary, and @|after| methods
739 occurs multiple times.
3cc520db 740
b1254eb6
MW
741 The value returned by the most specific @|around| method is the value
742 returned by the effective method.
3cc520db 743
8ec911fa 744\item If any applicable methods have the @|before| rôle, then they are all
3cc520db
MW
745 invoked, starting with the most specific.
746
747\item The most specific applicable primary method is invoked.
748
749 Within the body of a primary method, the variable @|next_method| is
750 defined, having pointer-to-function type. If there are no remaining less
751 specific primary methods, then @|next_method| is a null pointer.
752 Otherwise, the method may call the @|next_method| function any number of
753 times.
754
755 The behaviour of the @|next_method| function, if it is not null, is to
756 invoke the next most specific applicable primary method, and to return
757 whichever value that method returns.
758
b1254eb6
MW
759 If there are no applicable @|around| methods, then the value returned by
760 the most specific primary method is the value returned by the effective
761 method; otherwise the value returned by the most specific primary method is
762 returned to the least specific @|around| method, which called it via its
763 own @|next_method| function.
3cc520db 764
8ec911fa 765\item If any applicable methods have the @|after| rôle, then they are all
3cc520db 766 invoked, starting with the \emph{least} specific. (Hence, the most
b1254eb6 767 specific @|after| method is invoked with the most `afterness'.)
3cc520db
MW
768
769\end{enumerate}
770
b1254eb6
MW
771A typical use for @|around| methods is to allow a base class to set up the
772dynamic environment appropriately for the primary methods of its subclasses,
756e9293 773e.g., by claiming a lock, and releasing it afterwards.
3cc520db 774
9761db0d 775The @|next_method| function provided to methods with the primary and
8ec911fa 776@|around| rôles accepts the same arguments, and returns the same type, as the
3cc520db
MW
777message, except that one or two additional arguments are inserted at the
778front of the argument list. The first additional argument is always the
779receiving object, @|me|. If the message accepts a variable argument suffix,
780then the second addition argument is a @|va_list|; otherwise there is no
781second additional argument; otherwise, In the former case, a variable
782@|sod__master_ap| of type @|va_list| is defined, containing a separate copy
783of the argument pointer (so the method body can process the variable argument
784suffix itself, and still pass a fresh copy on to the next method).
785
8ec911fa 786A method with the primary or @|around| rôle may use the convenience macro
3cc520db
MW
787@|CALL_NEXT_METHOD|, which takes no arguments itself, and simply calls
788@|next_method| with appropriate arguments: the receiver @|me| pointer, the
789argument pointer @|sod__master_ap| (if applicable), and the method's
790arguments. If the method body has overwritten its formal arguments, then
791@|CALL_NEXT_METHOD| will pass along the updated values, rather than the
792original ones.
793
781a8fbd
MW
794A primary or @|around| method which invokes its @|next_method| function is
795said to \emph{extend} the message behaviour; a method which does not invoke
796its @|next_method| is said to \emph{override} the behaviour. Note that a
797method may make a decision to override or extend at runtime.
798
43073476 799\subsubsection{Aggregating method combinations}
3cc520db
MW
800A number of other method combinations are provided. They are called
801`aggregating' method combinations because, instead of invoking just the most
802specific primary method, as the standard method combination does, they invoke
803the applicable primary methods in turn and aggregate the return values from
804each.
805
8ec911fa 806The aggregating method combinations accept the same four rôles as the
b1254eb6
MW
807standard method combination, and @|around|, @|before|, and @|after| methods
808work in the same way.
3cc520db
MW
809
810The aggregating method combinations provided are as follows.
811\begin{description} \let\makelabel\code
812\item[progn] The message must return @|void|. The applicable primary methods
813 are simply invoked in turn, most specific first.
814\item[sum] The message must return a numeric type.\footnote{%
815 The Sod translator does not check this, since it doesn't have enough
816 insight into @|typedef| names.} %
817 The applicable primary methods are invoked in turn, and their return values
818 added up. The final result is the sum of the individual values.
819\item[product] The message must return a numeric type. The applicable
820 primary methods are invoked in turn, and their return values multiplied
821 together. The final result is the product of the individual values.
822\item[min] The message must return a scalar type. The applicable primary
823 methods are invoked in turn. The final result is the smallest of the
824 individual values.
825\item[max] The message must return a scalar type. The applicable primary
826 methods are invoked in turn. The final result is the largest of the
827 individual values.
665a0455
MW
828\item[and] The message must return a scalar type. The applicable primary
829 methods are invoked in turn. If any method returns zero then the final
830 result is zero and no further methods are invoked. If all of the
831 applicable primary methods return nonzero, then the final result is the
832 result of the last primary method.
833\item[or] The message must return a scalar type. The applicable primary
834 methods are invoked in turn. If any method returns nonzero then the final
835 result is that nonzero value and no further methods are invoked. If all of
836 the applicable primary methods return zero, then the final result is zero.
3cc520db
MW
837\end{description}
838
839There is also a @|custom| aggregating method combination, which is described
840in \xref{sec:fixme.custom-aggregating-method-combination}.
841
43073476 842
f4e44f7f 843\subsection{Method entries} \label{sec:concepts.methods.entry}
caa6f4b9 844
caa6f4b9
MW
845The effective methods for each class are determined at translation time, by
846the Sod translator. For each effective method, one or more \emph{method
847entry functions} are constructed. A method entry function has three
848responsibilities.
849\begin{itemize}
850\item It converts the receiver pointer to the correct type. Method entry
851 functions can perform these conversions extremely efficiently: there are
852 separate method entries for each chain of each class which can receive a
853 message, so method entry functions are in the privileged situation of
854 knowing the \emph{exact} class of the receiving object.
855\item If the message accepts a variable-length argument tail, then two method
856 entry functions are created for each chain of each class: one receives a
857 variable-length argument tail, as intended, and captures it in a @|va_list|
858 object; the other accepts an argument of type @|va_list| in place of the
859 variable-length tail and arranges for it to be passed along to the direct
860 methods.
861\item It invokes the effective method with the appropriate arguments. There
862 might or might not be an actual function corresponding to the effective
863 method itself: the translator may instead open-code the effective method's
864 behaviour into each method entry function; and the machinery for handling
865 `delegation chains', such as is used for @|around| methods and primary
866 methods in the standard method combination, is necessarily scattered among
867 a number of small functions.
868\end{itemize}
869
870
43073476
MW
871\subsection{Messages with keyword arguments}
872\label{sec:concepts.methods.keywords}
873
874A message or a direct method may declare that it accepts keyword arguments.
875A message which accepts keyword arguments is called a \emph{keyword message};
876a direct method which accepts keyword arguments is called a \emph{keyword
877method}.
878
879While method combinations may set their own rules, usually keyword methods
880can only be defined on keyword messages, and all methods defined on a keyword
881message must be keyword methods. The direct methods defined on a keyword
882message may differ in the keywords they accept, both from each other, and
bf2e7452
MW
883from the message. If two applicable methods on the same message both accept
884a keyword argument with the same name, then these two keyword arguments must
885also have the same type. Different applicable methods may declare keyword
886arguments with the same name but different defaults; see below.
43073476
MW
887
888The keyword arguments acceptable in a message sent to an object are the
889keywords listed in the message definition, together with all of the keywords
890accepted by any applicable method. There is no easy way to determine at
891runtime whether a particular keyword is acceptable in a message to a given
892instance.
893
894At runtime, a direct method which accepts one or more keyword arguments
895receives an additional argument named @|suppliedp|. This argument is a small
896structure. For each keyword argument named $k$ accepted by the direct
897method, @|suppliedp| contains a one-bit-wide bitfield member of type
898@|unsigned|, also named $k$. If a keyword argument named $k$ was passed in
899the message, then @|suppliedp.$k$| is one, and $k$ contains the argument
900value; otherwise @|suppliedp.$k$| is zero, and $k$ contains the default value
901from the direct method definition if there was one, or an unspecified value
902otherwise.
903
3cc520db 904%%%--------------------------------------------------------------------------
d24d47f5
MW
905\section{The object lifecycle} \label{sec:concepts.lifecycle}
906
907\subsection{Creation} \label{sec:concepts.lifecycle.birth}
908
909Construction of a new instance of a class involves three steps.
910\begin{enumerate}
911\item \emph{Allocation} arranges for there to be storage space for the
912 instance's slots and associated metadata.
913\item \emph{Imprinting} fills in the instance's metadata, associating the
914 instance with its class.
915\item \emph{Initialization} stores appropriate initial values in the
916 instance's slots, and maybe links it into any external data structures as
917 necessary.
918\end{enumerate}
919The \descref{SOD_DECL}[macro]{mac} handles constructing instances with
a42893dd
MW
920automatic storage duration (`on the stack'). Similarly, the
921\descref{SOD_MAKE}[macro]{mac} and the \descref{sod_make}{fun} and
922\descref{sod_makev}{fun} functions construct instances allocated from the
923standard @|malloc| heap. Programmers can add support for other allocation
924strategies by using the \descref{SOD_INIT}[macro]{mac} and the
925\descref{sod_init}{fun} and \descref{sod_initv}{fun} functions, which package
926up imprinting and initialization.
d24d47f5
MW
927
928\subsubsection{Allocation}
929Instances of most classes (specifically including those classes defined by
930Sod itself) can be held in any storage of sufficient size. The in-memory
931layout of an instance of some class~$C$ is described by the type @|struct
932$C$__ilayout|, and if the relevant class is known at compile time then the
933best way to discover the layout size is with the @|sizeof| operator. Failing
934that, the size required to hold an instance of $C$ is available in a slot in
935$C$'s class object, as @|$C$__class@->cls.initsz|.
936
937It is not in general sufficient to declare, or otherwise allocate, an object
938of the class type $C$. The class type only describes a single chain of the
939object's layout. It is nearly always an error to use the class type as if it
940is a \emph{complete type}, e.g., to declare objects or arrays of the class
941type, or to enquire about its size or alignment requirements.
942
943Instance layouts may be declared as objects with automatic storage duration
944(colloquially, `allocated on the stack') or allocated dynamically, e.g.,
945using @|malloc|. They may be included as members of structures or unions, or
946elements of arrays. Sod's runtime system doesn't retain addresses of
947instances, so, for example, Sod doesn't make using fancy allocators which
948sometimes move objects around in memory any more difficult than it needs to
949be.
950
951There isn't any way to discover the alignment required for a particular
952class's instances at runtime; it's best to be conservative and assume that
953the platform's strictest alignment requirement applies.
954
955The following simple function correctly allocates and returns space for an
956instance of a class given a pointer to its class object @<cls>.
957\begin{prog}
020b9e2b 958 void *allocate_instance(const SodClass *cls) \\ \ind
d24d47f5
MW
959 \{ return malloc(cls@->cls.initsz); \}
960\end{prog}
961
962\subsubsection{Imprinting}
963Once storage has been allocated, it must be \emph{imprinted} before it can be
964used as an instance of a class, e.g., before any messages can be sent to it.
965
966Imprinting an instance stores some metadata about its direct class in the
967instance structure, so that the rest of the program (and Sod's runtime
968library) can tell what sort of object it is, and how to use it.\footnote{%
969 Specifically, imprinting an instance's storage involves storing the
970 appropriate vtable pointers in the right places in it.} %
971A class object's @|imprint| slot points to a function which will correctly
972imprint storage for one of that class's instances.
973
974Once an instance's storage has been imprinted, it is technically possible to
975send messages to the instance; however the instance's slots are still
756e9293
MW
976uninitialized at this point, so the applicable methods are unlikely to do
977much of any use unless they've been written specifically for the purpose.
d24d47f5
MW
978
979The following simple function imprints storage at address @<p> as an instance
980of a class, given a pointer to its class object @<cls>.
981\begin{prog}
020b9e2b 982 void imprint_instance(const SodClass *cls, void *p) \\ \ind
d24d47f5
MW
983 \{ cls@->cls.imprint(p); \}
984\end{prog}
985
986\subsubsection{Initialization}
987The final step for constructing a new instance is to \emph{initialize} it, to
988establish the necessary invariants for the instance itself and the
989environment in which it operates.
990
991Details of initialization are necessarily class-specific, but typically it
992involves setting the instance's slots to appropriate values, and possibly
d1b394fa
MW
993linking it into some larger data structure to keep track of it. It is
994possible for initialization methods to attempt to allocate resources, but
995this must be done carefully: there is currently no way to report an error
996from object initialization, so the object must be marked as incompletely
997initialized, and left in a state where it will be safe to tear down later.
d24d47f5 998
a142609c
MW
999Initialization is performed by sending the imprinted instance an @|init|
1000message, defined by the @|SodObject| class. This message uses a nonstandard
1001method combination which works like the standard combination, except that the
1002\emph{default behaviour}, if there is no overriding method, is to initialize
b2983f35
MW
1003the instance's slots, as described below, and to invoke each superclass's
1004initialization fragments. This default behaviour may be invoked multiple
1005times if some method calls on its @|next_method| more than once, unless some
1006other method takes steps to prevent this.
a142609c 1007
27ec3825
MW
1008Slots are initialized in a well-defined order.
1009\begin{itemize}
054e8f8f
MW
1010\item Slots defined by a more specific superclass are initialized after slots
1011 defined by a less specific superclass.
27ec3825
MW
1012\item Slots defined by the same class are initialized in the order in which
1013 their definitions appear.
1014\end{itemize}
1015
a42893dd
MW
1016A class can define \emph{initialization fragments}: pieces of literal code to
1017be executed to set up a new instance. Each superclass's initialization
1018fragments are executed with @|me| bound to an instance pointer of the
1019appropriate superclass type, immediately after that superclass's slots (if
1020any) have been initialized; therefore, fragments defined by a more specific
13cb243a 1021superclass are executed after fragments defined by a less specific
a42893dd
MW
1022superclass. A class may define more than one initialization fragment: the
1023fragments are executed in the order in which they appear in the class
1024definition. It is possible for an initialization fragment to use @|return|
1025or @|goto| for special control-flow effects, but this is not likely to be a
1026good idea.
1027
b2983f35
MW
1028The @|init| message accepts keyword arguments
1029(\xref{sec:concepts.methods.keywords}). The set of acceptable keywords is
1030determined by the applicable methods as usual, but also by the
1031\emph{initargs} defined by the receiving instance's class and its
1032superclasses, which are made available to slot initializers and
1033initialization fragments.
1034
1035There are two kinds of initarg definitions. \emph{User initargs} are defined
1036by an explicit @|initarg| item appearing in a class definition: the item
1037defines a name, type, and (optionally) a default value for the initarg.
1038\emph{Slot initargs} are defined by attaching an @|initarg| property to a
756e9293
MW
1039slot or slot initializer item: the property's value determines the initarg's
1040name, while the type is taken from the underlying slot type; slot initargs do
1041not have default values. Both kinds define a \emph{direct initarg} for the
b2983f35
MW
1042containing class.
1043
1044Initargs are inherited. The \emph{applicable} direct initargs for an @|init|
1045effective method are those defined by the receiving object's class, and all
1046of its superclasses. Applicable direct initargs with the same name are
1047merged to form \emph{effective initargs}. An error is reported if two
1048applicable direct initargs have the same name but different types. The
1049default value of an effective initarg is taken from the most specific
1050applicable direct initarg which specifies a defalt value; if no applicable
1051direct initarg specifies a default value then the effective initarg has no
1052default.
1053
1054All initarg values are made available at runtime to user code --
1055initialization fragments and slot initializer expressions -- through local
1056variables and a @|suppliedp| structure, as in a direct method
1057(\xref{sec:concepts.methods.keywords}). Furthermore, slot initarg
1058definitions influence the initialization of slots.
1059
1060The process for deciding how to initialize a particular slot works as
1061follows.
1062\begin{enumerate}
1063\item If there are any slot initargs defined on the slot, or any of its slot
1064 initializers, \emph{and} the sender supplied a value for one or more of the
1065 corresponding effective initargs, then the value of the most specific slot
1066 initarg is stored in the slot.
1067\item Otherwise, if there are any slot initializers defined which include an
1068 initializer expression, then the initializer expression from the most
1069 specific such slot initializer is evaluated and its value stored in the
1070 slot.
1071\item Otherwise, the slot is left uninitialized.
1072\end{enumerate}
1073Note that the default values (if any) of effective initargs do \emph{not}
1074affect this procedure.
d24d47f5 1075
d24d47f5
MW
1076
1077\subsection{Destruction}
1078\label{sec:concepts.lifecycle.death}
1079
1080Destruction of an instance, when it is no longer required, consists of two
1081steps.
1082\begin{enumerate}
1083\item \emph{Teardown} releases any resources held by the instance and
1084 disentangles it from any external data structures.
1085\item \emph{Deallocation} releases the memory used to store the instance so
1086 that it can be reused.
1087\end{enumerate}
a42893dd
MW
1088Teardown alone, for objects which require special deallocation, or for which
1089deallocation occurs automatically (e.g., instances with automatic storage
1090duration, or instances whose storage will be garbage-collected), is performed
1091using the \descref{sod_teardown}[function]{fun}. Destruction of instances
1092allocated from the standard @|malloc| heap is done using the
1093\descref{sod_destroy}[function]{fun}.
d24d47f5
MW
1094
1095\subsubsection{Teardown}
7646dc4c
MW
1096Details of teardown are necessarily class-specific, but typically it
1097involves releasing resources held by the instance, and disentangling it from
1098any data structures it might be linked into.
a42893dd
MW
1099
1100Teardown is performed by sending the instance the @|teardown| message,
1101defined by the @|SodObject| class. The message returns an integer, used as a
1102boolean flag. If the message returns zero, then the instance's storage
1103should be deallocated. If the message returns nonzero, then it is safe for
1104the caller to forget about instance, but should not deallocate its storage.
1105This is \emph{not} an error return: if some teardown method fails then the
1106program may be in an inconsistent state and should not continue.
d24d47f5 1107
a42893dd
MW
1108This simple protocol can be used, for example, to implement a reference
1109counting system, as follows.
d24d47f5 1110\begin{prog}
020b9e2b 1111 [nick = ref] \\
d7451ac3 1112 class ReferenceCountedObject: SodObject \{ \\ \ind
020b9e2b
MW
1113 unsigned nref = 1; \\-
1114 void inc() \{ me@->ref.nref++; \} \\-
1115 [role = around] \\
1116 int obj.teardown() \\
1117 \{ \\ \ind
1118 if (--\,--me@->ref.nref) return (1); \\
1119 else return (CALL_NEXT_METHOD); \-\\
1120 \} \-\\
d24d47f5
MW
1121 \}
1122\end{prog}
1123
fa7e2d72
MW
1124The @|teardown| message uses a nonstandard method combination which works
1125like the standard combination, except that the \emph{default behaviour}, if
1126there is no overriding method, is to execute the superclass's teardown
1127fragments, and to return zero. This default behaviour may be invoked
1128multiple times if some method calls on its @|next_method| more than once,
1129unless some other method takes steps to prevent this.
a42893dd
MW
1130
1131A class can define \emph{teardown fragments}: pieces of literal code to be
1132executed to shut down an instance. Each superclass's teardown fragments are
1133executed with @|me| bound to an instance pointer of the appropriate
1134superclass type; fragments defined by a more specific superclass are executed
13cb243a 1135before fragments defined by a less specific superclass. A class may define
a42893dd
MW
1136more than one teardown fragment: the fragments are executed in the order in
1137which they appear in the class definition. It is possible for an
1138initialization fragment to use @|return| or @|goto| for special control-flow
1139effects, but this is not likely to be a good idea. Similarly, it's probably
1140a better idea to use an @|around| method to influence the return value than
1141to write an explicit @|return| statement in a teardown fragment.
1142
d24d47f5
MW
1143\subsubsection{Deallocation}
1144The details of instance deallocation are obviously specific to the allocation
1145strategy used by the instance, and this is often orthogonal from the object's
1146class.
1147
1148The code which makes the decision to destroy an object may often not be aware
1149of the object's direct class. Low-level details of deallocation often
1150require the proper base address of the instance's storage, which can be
1151determined using the \descref{SOD_INSTBASE}[macro]{mac}.
1152
d24d47f5 1153%%%--------------------------------------------------------------------------
3cc520db 1154\section{Metaclasses} \label{sec:concepts.metaclasses}
1f7d590d 1155
71efc524
MW
1156In Sod, every object is an instance of some class, and -- unlike, say,
1157\Cplusplus\ -- classes are proper objects. It follows that, in Sod, every
1158class~$C$ is itself an instance of some class~$M$, which is called $C$'s
1159\emph{metaclass}. Metaclass instances are usually constructed statically, at
1160compile time, and marked read-only.
1161
1162As an added complication, Sod classes, and other metaobjects such as
1163messages, methods, slots and so on, also have classes \emph{at translation
1164time}. These translation-time metaclasses are not Sod classes; they are CLOS
1165classes, implemented in Common Lisp.
1166
1167
1168\subsection{Runtime metaclasses}
1169\label{sec:concepts.metaclasses.runtime}
1170
1171Like other classes, metaclasses can declare messages, and define slots and
1172methods. Slots defined by the metaclass are called \emph{class slots}, as
1173opposed to \emph{instance slots}. Similarly, messages and methods defined by
1174the metaclass are termed \emph{class messages} and \emph{class methods}
1175respectively, though these are used much less frequently.
1176
1177\subsubsection{The braid}
1178Every object is an instance of some class. There are only finitely many
1179classes.
1180
1181\begin{figure}
1182 \centering
1183 \begin{tikzpicture}
1184 \node[lit] (obj) {SodObject};
1185 \node[lit] (cls) [right=10mm of obj] {SodClass};
1186 \draw [->, dashed] (obj) to[bend right] (cls);
1187 \draw [->] (cls) to[bend right] (obj);
1188 \draw [->, dashed] (cls) to[loop right] (cls);
1189 \end{tikzpicture}
1190 \qquad
1191 \fbox{\ \begin{tikzpicture}
1192 \node (subclass) {subclass of};
1193 \node (instance) [below=\jot of subclass] {instance of};
1194 \draw [->] ($(subclass.west) - (10mm, 0)$) -- ++(8mm, 0);
1195 \draw [->, dashed] ($(instance.west) - (10mm, 0)$) -- ++(8mm, 0);
1196 \end{tikzpicture}}
1197 \caption{The Sod braid} \label{fig:concepts.metaclasses.braid}
1198\end{figure}
1199
1200Consider the directed graph whose nodes are classes, and where there is an
1201arc from $C$ to $D$ if and only if $C$ is an instance of $D$. There are only
1202finitely many nodes. Every node has an arc leaving it, because every object
1203-- and hence every class -- is an instance of some class. Therefore this
1204graph must contain at least one cycle.
1205
1206In Sod, this situation is resolved in the simplest manner possible:
1207@|SodClass| is the only predefined metaclass, and it is an instance of
1208itself. The only other predefined class is @|SodObject|, which is also an
1209instance of @|SodClass|. There is exactly one root class, namely
1210@|SodObject|; consequently, @|SodClass| is a direct subclass of @|SodObject|.
1211
1212\Xref{fig:concepts.metaclasses.braid} shows a diagram of this situation.
1213
1214\subsubsection{Class slots and initializers}
1215Instance initializers were described in \xref{sec:concepts.classes.slots}. A
1216class can also define \emph{class initializers}, which provide values for
1217slots defined by its metaclass. The initial value for a class slot is
1218determined as follows.
1219\begin{itemize}
1220\item Nonstandard slot classes may be initialized by custom Lisp code. For
1221 example, all of the slots defined by @|SodClass| are of this kind. User
1222 initializers are not permitted for such slots.
1223\item If the class or any of its superclasses defines a class initializer for
1224 the slot, then the class initializer defined by the most specific such
1225 superclass is used.
1226\item Otherwise, if the metaclass or one of its superclasses defines an
1227 instance initializer, then the instance initializer defined by he most
1228 specific such class is used.
1229\item Otherwise there is no initializer, and an error will be reported.
1230\end{itemize}
1231Initializers for class slots must be constant expressions (for scalar slots)
1232or aggregate initializers containing constant expressions.
1233
1234\subsubsection{Metaclass selection and consistency}
1235Sod enforces a \emph{metaclass consistency rule}: if $C$ has metaclass $M$,
1236then any subclass $C$ must have a metaclass which is a subclass of $M$.
1237
1238The definition of a new class can name the new class's metaclass explicitly,
1239by defining a @|metaclass| property; the Sod translator will verify that the
1240choice of metaclass is acceptable.
1241
1242If no @|metaclass| property is given, then the translator will select a
1243default metaclass as follows. Let $C_1$, $C_2$, \dots, $C_n$ be the direct
1244superclasses of the new class, and let $M_1$, $M_2$, \dots, $M_n$ be their
1245respective metaclasses (not necessarily distinct). If there exists exactly
1246one minimal metaclass $M_i$, i.e., there exists an $i$, with $1 \le i \le n$,
1247such that $M_i$ is a subclass of every $M_j$, for $1 \le j \le n$, then $M_i$
1248is selected as the new class's metaclass. Otherwise the situation is
1249ambiguous and an error will be reported. Usually, the ambiguity can be
1250resolved satisfactorily by defining a new class $M^*$ as a direct subclass of
1251the minimal $M_j$.
1252
1253
1254\subsection{Translation-time metaobjects}
1255\label{sec:concepts.metaclasses.compile-time}
1256
1257
1258
1259\fixme{unwritten}
1260
caa6f4b9
MW
1261%%%--------------------------------------------------------------------------
1262\section{Compatibility considerations} \label{sec:concepts.compatibility}
1263
1264Sod doesn't make source-level compatibility especially difficult. As long as
1265classes, slots, and messages don't change names or dissappear, and slots and
1266messages retain their approximate types, everything will be fine.
1267
1268Binary compatibility is much more difficult. Unfortunately, Sod classes have
1269rather fragile binary interfaces.\footnote{%
1270 Research suggestion: investigate alternative instance and vtable layouts
1271 which improve binary compatibility, probably at the expense of instance
1272 compactness, and efficiency of slot access and message sending. There may
1273 be interesting trade-offs to be made.} %
1274
6390b845 1275If instances are allocated \fixme{incomplete}
caa6f4b9 1276
1f7d590d
MW
1277%%%----- That's all, folks --------------------------------------------------
1278
1279%%% Local variables:
1280%%% mode: LaTeX
1281%%% TeX-master: "sod.tex"
1282%%% TeX-PDF-mode: t
1283%%% End: