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