chiark / gitweb /
doc/concepts.tex: A number of minor fixes.
[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
MW
28%%%--------------------------------------------------------------------------
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
125If $C$ has a proper superclass $B$, then $B$ is not allowed to have $C$ has a
126direct superclass. In different terms, if we construct a graph, whose
127vertices are classes, and draw an edge 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.
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,
151which has a number of good properties described in~\cite{FIXME:C3}.
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
173\subsubsection{Class links and chains}
174The definition for a class $C$ may distinguish one of its proper superclasses
175as being the \emph{link superclass} for class $C$. Not every class need have
176a link superclass, and the link superclass of a class $C$, if it exists, need
177not be a direct superclass of $C$.
178
179Superclass links must obey the following rule: if $C$ is a class, then there
781a8fbd
MW
180must be no three superclasses $X$, $Y$ and~$Z$ of $C$ such that $Z$ is the
181link superclass of both $X$ and $Y$. As a consequence of this rule, the
3cc520db
MW
182superclasses of $C$ can be partitioned into linear \emph{chains}, such that
183superclasses $A$ and $B$ are in the same chain if and only if one can trace a
184path from $A$ to $B$ by following superclass links, or \emph{vice versa}.
185
186Since a class links only to one of its proper superclasses, the classes in a
187chain are naturally ordered from most- to least-specific. The least specific
188class in a chain is called the \emph{chain head}; the most specific class is
189the \emph{chain tail}. Chains are often named after their chain head
190classes.
191
192\subsection{Names}
193\label{sec:concepts.classes.names}
194
195Classes have a number of other attributes:
196\begin{itemize}
197\item A \emph{name}, which is a C identifier. Class names must be globally
198 unique. The class name is used in the names of a number of associated
199 definitions, to be described later.
200\item A \emph{nickname}, which is also a C identifier. Unlike names,
201 nicknames are not required to be globally unique. If $C$ is any class,
202 then all the superclasses of $C$ must have distinct nicknames.
203\end{itemize}
204
0a2d4b68 205
3cc520db
MW
206\subsection{Slots} \label{sec:concepts.classes.slots}
207
208Each class defines a number of \emph{slots}. Much like a structure member, a
209slot has a \emph{name}, which is a C identifier, and a \emph{type}. Unlike
210many other object systems, different superclasses of a class $C$ can define
211slots with the same name without ambiguity, since slot references are always
212qualified by the defining class's nickname.
213
214\subsubsection{Slot initializers}
215As well as defining slot names and types, a class can also associate an
216\emph{initial value} with each slot defined by itself or one of its
217subclasses. A class $C$ provides an \emph{initialization function} (see
d24d47f5
MW
218\xref{sec:concepts.lifecycle.birth}, and \xref{sec:structures.root.sodclass})
219which sets the slots of a \emph{direct} instance of the class to the correct
3cc520db
MW
220initial values. If several of $C$'s superclasses define initializers for the
221same slot then the initializer from the most specific such class is used. If
222none of $C$'s superclasses define an initializer for some slot then that slot
781a8fbd 223will be left uninitialized.
3cc520db
MW
224
225The initializer for a slot with scalar type may be any C expression. The
226initializer for a slot with aggregate type must contain only constant
227expressions if the generated code is expected to be processed by a
228implementation of C89. Initializers will be evaluated once each time an
229instance is initialized.
230
27ec3825
MW
231Slots are initialized in reverse-precedence order of their defining classes;
232i.e., slots defined by a less specific superclass are initialized earlier
233than slots defined by a more specific superclass. Slots defined by the same
234class are initialized in the order in which they appear in the class
235definition.
236
237The initializer for a slot may refer to other slots in the same object, via
238the @|me| pointer: in an initializer for a slot defined by a class $C$, @|me|
239has type `pointer to $C$'. (Note that the type of @|me| depends only on the
240class which defined the slot, not the class which defined the initializer.)
241
0a2d4b68 242
3cc520db
MW
243\subsection{C language integration} \label{sec:concepts.classes.c}
244
245For each class~$C$, the Sod translator defines a C type, the \emph{class
246type}, with the same name. This is the usual type used when considering an
247object as an instance of class~$C$. No entire object will normally have a
248class type,\footnote{%
249 In general, a class type only captures the structure of one of the
250 superclass chains of an instance. A full instance layout contains multiple
251 chains. See \xref{sec:structures.layout} for the full details.} %
252so access to instances is almost always via pointers.
253
254\subsubsection{Access to slots}
255The class type for a class~$C$ is actually a structure. It contains one
256member for each class in $C$'s superclass chain, named with that class's
257nickname. Each of these members is also a structure, containing the
258corresponding class's slots, one member per slot. There's nothing special
259about these slot members: C code can access them in the usual way.
260
261For example, if @|MyClass| has the nickname @|mine|, and defines a slot @|x|
262of type @|int|, then the simple function
263\begin{prog}
c18d6aba 264 int get_x(MyClass *m) \{ return (m@->mine.x); \}
3cc520db
MW
265\end{prog}
266will extract the value of @|x| from an instance of @|MyClass|.
267
268All of this means that there's no such thing as `private' or `protected'
269slots. If you want to hide implementation details, the best approach is to
270stash them in a dynamically allocated private structure, and leave a pointer
271to it in a slot. (This will also help preserve binary compatibility, because
272the private structure can grow more members as needed. See
e4ea29d8 273\xref{sec:fixme.compatibility} for more details.)
3cc520db 274
caa6f4b9
MW
275\subsubsection{Vtables}
276
277
3cc520db
MW
278\subsubsection{Class objects}
279In Sod's object system, classes are objects too. Therefore classes are
280themselves instances; the class of a class is called a \emph{metaclass}. The
281consequences of this are explored in \xref{sec:concepts.metaclasses}. The
282\emph{class object} has the same name as the class, suffixed with
283`@|__class|'\footnote{%
284 This is not quite true. @|$C$__class| is actually a macro. See
285 \xref{sec:structures.layout.additional} for the gory details.} %
286and its type is usually @|SodClass|; @|SodClass|'s nickname is @|cls|.
287
288A class object's slots contain or point to useful information, tables and
289functions for working with that class's instances. (The @|SodClass| class
290doesn't define any messages, so it doesn't have any methods. In Sod, a class
291slot containing a function pointer is not at all the same thing as a method.)
292
3cc520db 293\subsubsection{Conversions}
e4ea29d8
MW
294Suppose one has a value of type pointer-to-class-type for some class~$C$, and
295wants to convert it to a pointer-to-class-type for some other class~$B$.
3cc520db
MW
296There are three main cases to distinguish.
297\begin{itemize}
298\item If $B$ is a superclass of~$C$, in the same chain, then the conversion
299 is an \emph{in-chain upcast}. The conversion can be performed using the
300 appropriate generated upcast macro (see below), or by simply casting the
301 pointer, using C's usual cast operator (or the \Cplusplus\ @|static_cast<>|
302 operator).
303\item If $B$ is a superclass of~$C$, in a different chain, then the
304 conversion is a \emph{cross-chain upcast}. The conversion is more than a
305 simple type change: the pointer value must be adjusted. If the direct
306 class of the instance in question is not known, the conversion will require
307 a lookup at runtime to find the appropriate offset by which to adjust the
308 pointer. The conversion can be performed using the appropriate generated
309 upcast macro (see below); the general case is handled by the macro
58f9b400 310 \descref{SOD_XCHAIN}{mac}.
e4ea29d8 311\item If $B$ is a subclass of~$C$ then the conversion is a \emph{downcast};
3cc520db
MW
312 otherwise the conversion is a~\emph{cross-cast}. In either case, the
313 conversion can fail: the object in question might not be an instance of~$B$
e4ea29d8 314 after all. The macro \descref{SOD_CONVERT}{mac} and the function
58f9b400 315 \descref{sod_convert}{fun} perform general conversions. They return a null
781a8fbd 316 pointer if the conversion fails. (There are therefore your analogue to the
e4ea29d8 317 \Cplusplus\ @|dynamic_cast<>| operator.)
3cc520db
MW
318\end{itemize}
319The Sod translator generates macros for performing both in-chain and
320cross-chain upcasts. For each class~$C$, and each proper superclass~$B$
321of~$C$, a macro is defined: given an argument of type pointer to class type
322of~$C$, it returns a pointer to the same instance, only with type pointer to
323class type of~$B$, adjusted as necessary in the case of a cross-chain
324conversion. The macro is named by concatenating
325\begin{itemize}
326\item the name of class~$C$, in upper case,
327\item the characters `@|__CONV_|', and
328\item the nickname of class~$B$, in upper case;
329\end{itemize}
330e.g., if $C$ is named @|MyClass|, and $B$'s name is @|SuperClass| with
331nickname @|super|, then the macro @|MYCLASS__CONV_SUPER| converts a
332@|MyClass~*| to a @|SuperClass~*|. See
333\xref{sec:structures.layout.additional} for the formal description.
334
335%%%--------------------------------------------------------------------------
9e91c8e7
MW
336\section{Keyword arguments} \label{sec:concepts.keywords}
337
338In standard C, the actual arguments provided to a function are matched up
339with the formal arguments given in the function definition according to their
340ordering in a list. Unless the (rather cumbersome) machinery for dealing
341with variable-length argument tails (@|<stdarg.h>|) is used, exactly the
342correct number of arguments must be supplied, and in the correct order.
343
344A \emph{keyword argument} is matched by its distinctive \emph{name}, rather
345than by its position in a list. Keyword arguments may be \emph{omitted},
346causing some default behaviour by the function. A function can detect
347whether a particular keyword argument was supplied: so the default behaviour
348need not be the same as that caused by any specific value of the argument.
349
350Keyword arguments can be provided in three ways.
351\begin{enumerate}
352\item Directly, as a variable-length argument tail, consisting (for the most
353 part) of alternating keyword names, as pointers to null-terminated strings,
354 and argument values, and terminated by a null pointer. This is somewhat
355 error-prone, and the support library defines some macros which help ensure
356 that keyword argument lists are well formed.
357\item Indirectly, through a @|va_list| object capturing a variable-length
358 argument tail passed to some other function. Such indirect argument tails
359 have the same structure as the direct argument tails described above.
360 Because @|va_list| objects are hard to copy, the keyword-argument support
361 library consistently passes @|va_list| objects \emph{by reference}
362 throughout its programming interface.
363\item Indirectly, through a vector of @|struct kwval| objects, each of which
364 contains a keyword name, as a pointer to a null-terminated string, and the
365 \emph{address} of a corresponding argument value. (This indirection is
366 necessary so that the items in the vector can be of uniform size.)
367 Argument vectors are rather inconvenient to use, but are the only practical
368 way in which a caller can decide at runtime which arguments to include in a
369 call, which is useful when writing wrapper functions.
370\end{enumerate}
371
372Keyword arguments are provided as a general feature for C functions.
43073476 373However, Sod has special support for messages which accept keyword arguments
a142609c
MW
374(\xref{sec:concepts.methods.keywords}); and they play an essential role in
375the instance construction protocol (\xref{sec:concepts.lifecycle.birth}).
9e91c8e7
MW
376
377%%%--------------------------------------------------------------------------
3cc520db
MW
378\section{Messages and methods} \label{sec:concepts.methods}
379
380Objects can be sent \emph{messages}. A message has a \emph{name}, and
381carries a number of \emph{arguments}. When an object is sent a message, a
382function, determined by the receiving object's class, is invoked, passing it
383the receiver and the message arguments. This function is called the
384class's \emph{effective method} for the message. The effective method can do
385anything a C function can do, including reading or updating program state or
386object slots, sending more messages, calling other functions, issuing system
387calls, or performing I/O; if it finishes, it may return a value, which is
388returned in turn to the message sender.
389
390The set of messages an object can receive, characterized by their names,
391argument types, and return type, is determined by the object's class. Each
392class can define new messages, which can be received by any instance of that
393class. The messages defined by a single class must have distinct names:
394there is no `function overloading'. As with slots
395(\xref{sec:concepts.classes.slots}), messages defined by distinct classes are
396always distinct, even if they have the same names: references to messages are
397always qualified by the defining class's name or nickname.
398
399Messages may take any number of arguments, of any non-array value type.
400Since message sends are effectively function calls, arguments of array type
401are implicitly converted to values of the corresponding pointer type. While
402message definitions may ascribe an array type to an argument, the formal
403argument will have pointer type, as is usual for C functions. A message may
404accept a variable-length argument suffix, denoted @|\dots|.
405
406A class definition may include \emph{direct methods} for messages defined by
407it or any of its superclasses.
408
409Like messages, direct methods define argument lists and return types, but
410they may also have a \emph{body}, and a \emph{role}.
411
412A direct method need not have the same argument list or return type as its
413message. The acceptable argument lists and return types for a method depend
414on the message, in particular its method combination
415(\xref{sec:concepts.methods.combination}), and the method's role.
416
417A direct method body is a block of C code, and the Sod translator usually
418defines, for each direct method, a function with external linkage, whose body
419contains a copy of the direct method body. Within the body of a direct
420method defined for a class $C$, the variable @|me|, of type pointer to class
421type of $C$, refers to the receiving object.
422
0a2d4b68 423
3cc520db
MW
424\subsection{Effective methods and method combinations}
425\label{sec:concepts.methods.combination}
426
427For each message a direct instance of a class might receive, there is a set
428of \emph{applicable methods}, which are exactly the direct methods defined on
429the object's class and its superclasses. These direct methods are combined
430together to form the \emph{effective method} for that particular class and
431message. Direct methods can be combined into an effective method in
432different ways, according to the \emph{method combination} specified by the
433message. The method combination determines which direct method roles are
434acceptable, and, for each role, the appropriate argument lists and return
435types.
436
437One direct method, $M$, is said to be more (resp.\ less) \emph{specific} than
438another, $N$, with respect to a receiving class~$C$, if the class defining
439$M$ is a more (resp.\ less) specific superclass of~$C$ than the class
440defining $N$.
441
43073476 442\subsubsection{The standard method combination}
3cc520db
MW
443The default method combination is called the \emph{standard method
444combination}; other method combinations are useful occasionally for special
445effects. The standard method combination accepts four direct method roles,
9761db0d 446called `primary' (the default), @|before|, @|after|, and @|around|.
3cc520db
MW
447
448All direct methods subject to the standard method combination must have
449argument lists which \emph{match} the message's argument list:
450\begin{itemize}
451\item the method's arguments must have the same types as the message, though
452 the arguments may have different names; and
453\item if the message accepts a variable-length argument suffix then the
454 direct method must instead have a final argument of type @|va_list|.
455\end{itemize}
b1254eb6
MW
456Primary and @|around| methods must have the same return type as the message;
457@|before| and @|after| methods must return @|void| regardless of the
458message's return type.
3cc520db
MW
459
460If there are no applicable primary methods then no effective method is
461constructed: the vtables contain null pointers in place of pointers to method
462entry functions.
463
464The effective method for a message with standard method combination works as
465follows.
466\begin{enumerate}
467
468\item If any applicable methods have the @|around| role, then the most
469 specific such method, with respect to the class of the receiving object, is
470 invoked.
471
b1254eb6 472 Within the body of an @|around| method, the variable @|next_method| is
3cc520db
MW
473 defined, having pointer-to-function type. The method may call this
474 function, as described below, any number of times.
475
b1254eb6
MW
476 If there any remaining @|around| methods, then @|next_method| invokes the
477 next most specific such method, returning whichever value that method
478 returns; otherwise the behaviour of @|next_method| is to invoke the before
479 methods (if any), followed by the most specific primary method, followed by
480 the @|around| methods (if any), and to return whichever value was returned
781a8fbd
MW
481 by the most specific primary method, as described in the following items.
482 That is, the behaviour of the least specific @|around| method's
483 @|next_method| function is exactly the behaviour that the effective method
484 would have if there were no @|around| methods. Note that if the
485 least-specific @|around| method calls its @|next_method| more than once
486 then the whole sequence of @|before|, primary, and @|after| methods occurs
487 multiple times.
3cc520db 488
b1254eb6
MW
489 The value returned by the most specific @|around| method is the value
490 returned by the effective method.
3cc520db
MW
491
492\item If any applicable methods have the @|before| role, then they are all
493 invoked, starting with the most specific.
494
495\item The most specific applicable primary method is invoked.
496
497 Within the body of a primary method, the variable @|next_method| is
498 defined, having pointer-to-function type. If there are no remaining less
499 specific primary methods, then @|next_method| is a null pointer.
500 Otherwise, the method may call the @|next_method| function any number of
501 times.
502
503 The behaviour of the @|next_method| function, if it is not null, is to
504 invoke the next most specific applicable primary method, and to return
505 whichever value that method returns.
506
b1254eb6
MW
507 If there are no applicable @|around| methods, then the value returned by
508 the most specific primary method is the value returned by the effective
509 method; otherwise the value returned by the most specific primary method is
510 returned to the least specific @|around| method, which called it via its
511 own @|next_method| function.
3cc520db
MW
512
513\item If any applicable methods have the @|after| role, then they are all
514 invoked, starting with the \emph{least} specific. (Hence, the most
b1254eb6 515 specific @|after| method is invoked with the most `afterness'.)
3cc520db
MW
516
517\end{enumerate}
518
b1254eb6
MW
519A typical use for @|around| methods is to allow a base class to set up the
520dynamic environment appropriately for the primary methods of its subclasses,
521e.g., by claiming a lock, and restore it afterwards.
3cc520db 522
9761db0d 523The @|next_method| function provided to methods with the primary and
3cc520db
MW
524@|around| roles accepts the same arguments, and returns the same type, as the
525message, except that one or two additional arguments are inserted at the
526front of the argument list. The first additional argument is always the
527receiving object, @|me|. If the message accepts a variable argument suffix,
528then the second addition argument is a @|va_list|; otherwise there is no
529second additional argument; otherwise, In the former case, a variable
530@|sod__master_ap| of type @|va_list| is defined, containing a separate copy
531of the argument pointer (so the method body can process the variable argument
532suffix itself, and still pass a fresh copy on to the next method).
533
9761db0d 534A method with the primary or @|around| role may use the convenience macro
3cc520db
MW
535@|CALL_NEXT_METHOD|, which takes no arguments itself, and simply calls
536@|next_method| with appropriate arguments: the receiver @|me| pointer, the
537argument pointer @|sod__master_ap| (if applicable), and the method's
538arguments. If the method body has overwritten its formal arguments, then
539@|CALL_NEXT_METHOD| will pass along the updated values, rather than the
540original ones.
541
781a8fbd
MW
542A primary or @|around| method which invokes its @|next_method| function is
543said to \emph{extend} the message behaviour; a method which does not invoke
544its @|next_method| is said to \emph{override} the behaviour. Note that a
545method may make a decision to override or extend at runtime.
546
43073476 547\subsubsection{Aggregating method combinations}
3cc520db
MW
548A number of other method combinations are provided. They are called
549`aggregating' method combinations because, instead of invoking just the most
550specific primary method, as the standard method combination does, they invoke
551the applicable primary methods in turn and aggregate the return values from
552each.
553
554The aggregating method combinations accept the same four roles as the
b1254eb6
MW
555standard method combination, and @|around|, @|before|, and @|after| methods
556work in the same way.
3cc520db
MW
557
558The aggregating method combinations provided are as follows.
559\begin{description} \let\makelabel\code
560\item[progn] The message must return @|void|. The applicable primary methods
561 are simply invoked in turn, most specific first.
562\item[sum] The message must return a numeric type.\footnote{%
563 The Sod translator does not check this, since it doesn't have enough
564 insight into @|typedef| names.} %
565 The applicable primary methods are invoked in turn, and their return values
566 added up. The final result is the sum of the individual values.
567\item[product] The message must return a numeric type. The applicable
568 primary methods are invoked in turn, and their return values multiplied
569 together. The final result is the product of the individual values.
570\item[min] The message must return a scalar type. The applicable primary
571 methods are invoked in turn. The final result is the smallest of the
572 individual values.
573\item[max] The message must return a scalar type. The applicable primary
574 methods are invoked in turn. The final result is the largest of the
575 individual values.
665a0455
MW
576\item[and] The message must return a scalar type. The applicable primary
577 methods are invoked in turn. If any method returns zero then the final
578 result is zero and no further methods are invoked. If all of the
579 applicable primary methods return nonzero, then the final result is the
580 result of the last primary method.
581\item[or] The message must return a scalar type. The applicable primary
582 methods are invoked in turn. If any method returns nonzero then the final
583 result is that nonzero value and no further methods are invoked. If all of
584 the applicable primary methods return zero, then the final result is zero.
3cc520db
MW
585\end{description}
586
587There is also a @|custom| aggregating method combination, which is described
588in \xref{sec:fixme.custom-aggregating-method-combination}.
589
43073476 590
caa6f4b9
MW
591\subsection{Sending messages in C} \label{sec:concepts.methods.c}
592
593Each instance is associated with its direct class [FIXME]
594
595The effective methods for each class are determined at translation time, by
596the Sod translator. For each effective method, one or more \emph{method
597entry functions} are constructed. A method entry function has three
598responsibilities.
599\begin{itemize}
600\item It converts the receiver pointer to the correct type. Method entry
601 functions can perform these conversions extremely efficiently: there are
602 separate method entries for each chain of each class which can receive a
603 message, so method entry functions are in the privileged situation of
604 knowing the \emph{exact} class of the receiving object.
605\item If the message accepts a variable-length argument tail, then two method
606 entry functions are created for each chain of each class: one receives a
607 variable-length argument tail, as intended, and captures it in a @|va_list|
608 object; the other accepts an argument of type @|va_list| in place of the
609 variable-length tail and arranges for it to be passed along to the direct
610 methods.
611\item It invokes the effective method with the appropriate arguments. There
612 might or might not be an actual function corresponding to the effective
613 method itself: the translator may instead open-code the effective method's
614 behaviour into each method entry function; and the machinery for handling
615 `delegation chains', such as is used for @|around| methods and primary
616 methods in the standard method combination, is necessarily scattered among
617 a number of small functions.
618\end{itemize}
619
620
43073476
MW
621\subsection{Messages with keyword arguments}
622\label{sec:concepts.methods.keywords}
623
624A message or a direct method may declare that it accepts keyword arguments.
625A message which accepts keyword arguments is called a \emph{keyword message};
626a direct method which accepts keyword arguments is called a \emph{keyword
627method}.
628
629While method combinations may set their own rules, usually keyword methods
630can only be defined on keyword messages, and all methods defined on a keyword
631message must be keyword methods. The direct methods defined on a keyword
632message may differ in the keywords they accept, both from each other, and
633from the message. If two superclasses of some common class both define
634keyword methods on the same message, and the methods both accept a keyword
635argument with the same name, then these two keyword arguments must also have
636the same type. Different applicable methods may declare keyword arguments
637with the same name but different defaults; see below.
638
639The keyword arguments acceptable in a message sent to an object are the
640keywords listed in the message definition, together with all of the keywords
641accepted by any applicable method. There is no easy way to determine at
642runtime whether a particular keyword is acceptable in a message to a given
643instance.
644
645At runtime, a direct method which accepts one or more keyword arguments
646receives an additional argument named @|suppliedp|. This argument is a small
647structure. For each keyword argument named $k$ accepted by the direct
648method, @|suppliedp| contains a one-bit-wide bitfield member of type
649@|unsigned|, also named $k$. If a keyword argument named $k$ was passed in
650the message, then @|suppliedp.$k$| is one, and $k$ contains the argument
651value; otherwise @|suppliedp.$k$| is zero, and $k$ contains the default value
652from the direct method definition if there was one, or an unspecified value
653otherwise.
654
d24d47f5
MW
655%%%--------------------------------------------------------------------------
656\section{The object lifecycle} \label{sec:concepts.lifecycle}
657
658\subsection{Creation} \label{sec:concepts.lifecycle.birth}
659
660Construction of a new instance of a class involves three steps.
661\begin{enumerate}
662\item \emph{Allocation} arranges for there to be storage space for the
663 instance's slots and associated metadata.
664\item \emph{Imprinting} fills in the instance's metadata, associating the
665 instance with its class.
666\item \emph{Initialization} stores appropriate initial values in the
667 instance's slots, and maybe links it into any external data structures as
668 necessary.
669\end{enumerate}
670The \descref{SOD_DECL}[macro]{mac} handles constructing instances with
a42893dd
MW
671automatic storage duration (`on the stack'). Similarly, the
672\descref{SOD_MAKE}[macro]{mac} and the \descref{sod_make}{fun} and
673\descref{sod_makev}{fun} functions construct instances allocated from the
674standard @|malloc| heap. Programmers can add support for other allocation
675strategies by using the \descref{SOD_INIT}[macro]{mac} and the
676\descref{sod_init}{fun} and \descref{sod_initv}{fun} functions, which package
677up imprinting and initialization.
d24d47f5
MW
678
679\subsubsection{Allocation}
680Instances of most classes (specifically including those classes defined by
681Sod itself) can be held in any storage of sufficient size. The in-memory
682layout of an instance of some class~$C$ is described by the type @|struct
683$C$__ilayout|, and if the relevant class is known at compile time then the
684best way to discover the layout size is with the @|sizeof| operator. Failing
685that, the size required to hold an instance of $C$ is available in a slot in
686$C$'s class object, as @|$C$__class@->cls.initsz|.
687
688It is not in general sufficient to declare, or otherwise allocate, an object
689of the class type $C$. The class type only describes a single chain of the
690object's layout. It is nearly always an error to use the class type as if it
691is a \emph{complete type}, e.g., to declare objects or arrays of the class
692type, or to enquire about its size or alignment requirements.
693
694Instance layouts may be declared as objects with automatic storage duration
695(colloquially, `allocated on the stack') or allocated dynamically, e.g.,
696using @|malloc|. They may be included as members of structures or unions, or
697elements of arrays. Sod's runtime system doesn't retain addresses of
698instances, so, for example, Sod doesn't make using fancy allocators which
699sometimes move objects around in memory any more difficult than it needs to
700be.
701
702There isn't any way to discover the alignment required for a particular
703class's instances at runtime; it's best to be conservative and assume that
704the platform's strictest alignment requirement applies.
705
706The following simple function correctly allocates and returns space for an
707instance of a class given a pointer to its class object @<cls>.
708\begin{prog}
020b9e2b 709 void *allocate_instance(const SodClass *cls) \\ \ind
d24d47f5
MW
710 \{ return malloc(cls@->cls.initsz); \}
711\end{prog}
712
713\subsubsection{Imprinting}
714Once storage has been allocated, it must be \emph{imprinted} before it can be
715used as an instance of a class, e.g., before any messages can be sent to it.
716
717Imprinting an instance stores some metadata about its direct class in the
718instance structure, so that the rest of the program (and Sod's runtime
719library) can tell what sort of object it is, and how to use it.\footnote{%
720 Specifically, imprinting an instance's storage involves storing the
721 appropriate vtable pointers in the right places in it.} %
722A class object's @|imprint| slot points to a function which will correctly
723imprint storage for one of that class's instances.
724
725Once an instance's storage has been imprinted, it is technically possible to
726send messages to the instance; however the instance's slots are still
727uninitialized at this point, the applicable methods are unlikely to do much
728of any use unless they've been written specifically for the purpose.
729
730The following simple function imprints storage at address @<p> as an instance
731of a class, given a pointer to its class object @<cls>.
732\begin{prog}
020b9e2b 733 void imprint_instance(const SodClass *cls, void *p) \\ \ind
d24d47f5
MW
734 \{ cls@->cls.imprint(p); \}
735\end{prog}
736
737\subsubsection{Initialization}
738The final step for constructing a new instance is to \emph{initialize} it, to
739establish the necessary invariants for the instance itself and the
740environment in which it operates.
741
742Details of initialization are necessarily class-specific, but typically it
743involves setting the instance's slots to appropriate values, and possibly
744linking it into some larger data structure to keep track of it.
745
a142609c
MW
746Initialization is performed by sending the imprinted instance an @|init|
747message, defined by the @|SodObject| class. This message uses a nonstandard
748method combination which works like the standard combination, except that the
749\emph{default behaviour}, if there is no overriding method, is to initialize
b2983f35
MW
750the instance's slots, as described below, and to invoke each superclass's
751initialization fragments. This default behaviour may be invoked multiple
752times if some method calls on its @|next_method| more than once, unless some
753other method takes steps to prevent this.
a142609c 754
27ec3825
MW
755Slots are initialized in a well-defined order.
756\begin{itemize}
757\item Slots defined by a more specific superclasses are initialized after
758 slots defined by a less specific superclass.
759\item Slots defined by the same class are initialized in the order in which
760 their definitions appear.
761\end{itemize}
762
a42893dd
MW
763A class can define \emph{initialization fragments}: pieces of literal code to
764be executed to set up a new instance. Each superclass's initialization
765fragments are executed with @|me| bound to an instance pointer of the
766appropriate superclass type, immediately after that superclass's slots (if
767any) have been initialized; therefore, fragments defined by a more specific
768superclass are executed after fragments defined by a more specific
769superclass. A class may define more than one initialization fragment: the
770fragments are executed in the order in which they appear in the class
771definition. It is possible for an initialization fragment to use @|return|
772or @|goto| for special control-flow effects, but this is not likely to be a
773good idea.
774
b2983f35
MW
775The @|init| message accepts keyword arguments
776(\xref{sec:concepts.methods.keywords}). The set of acceptable keywords is
777determined by the applicable methods as usual, but also by the
778\emph{initargs} defined by the receiving instance's class and its
779superclasses, which are made available to slot initializers and
780initialization fragments.
781
782There are two kinds of initarg definitions. \emph{User initargs} are defined
783by an explicit @|initarg| item appearing in a class definition: the item
784defines a name, type, and (optionally) a default value for the initarg.
785\emph{Slot initargs} are defined by attaching an @|initarg| property to a
786slot or slot initializer item: the property's determines the initarg's name,
787while the type is taken from the underlying slot type; slot initargs do not
788have default values. Both kinds define a \emph{direct initarg} for the
789containing class.
790
791Initargs are inherited. The \emph{applicable} direct initargs for an @|init|
792effective method are those defined by the receiving object's class, and all
793of its superclasses. Applicable direct initargs with the same name are
794merged to form \emph{effective initargs}. An error is reported if two
795applicable direct initargs have the same name but different types. The
796default value of an effective initarg is taken from the most specific
797applicable direct initarg which specifies a defalt value; if no applicable
798direct initarg specifies a default value then the effective initarg has no
799default.
800
801All initarg values are made available at runtime to user code --
802initialization fragments and slot initializer expressions -- through local
803variables and a @|suppliedp| structure, as in a direct method
804(\xref{sec:concepts.methods.keywords}). Furthermore, slot initarg
805definitions influence the initialization of slots.
806
807The process for deciding how to initialize a particular slot works as
808follows.
809\begin{enumerate}
810\item If there are any slot initargs defined on the slot, or any of its slot
811 initializers, \emph{and} the sender supplied a value for one or more of the
812 corresponding effective initargs, then the value of the most specific slot
813 initarg is stored in the slot.
814\item Otherwise, if there are any slot initializers defined which include an
815 initializer expression, then the initializer expression from the most
816 specific such slot initializer is evaluated and its value stored in the
817 slot.
818\item Otherwise, the slot is left uninitialized.
819\end{enumerate}
820Note that the default values (if any) of effective initargs do \emph{not}
821affect this procedure.
d24d47f5 822
d24d47f5
MW
823
824\subsection{Destruction}
825\label{sec:concepts.lifecycle.death}
826
827Destruction of an instance, when it is no longer required, consists of two
828steps.
829\begin{enumerate}
830\item \emph{Teardown} releases any resources held by the instance and
831 disentangles it from any external data structures.
832\item \emph{Deallocation} releases the memory used to store the instance so
833 that it can be reused.
834\end{enumerate}
a42893dd
MW
835Teardown alone, for objects which require special deallocation, or for which
836deallocation occurs automatically (e.g., instances with automatic storage
837duration, or instances whose storage will be garbage-collected), is performed
838using the \descref{sod_teardown}[function]{fun}. Destruction of instances
839allocated from the standard @|malloc| heap is done using the
840\descref{sod_destroy}[function]{fun}.
d24d47f5
MW
841
842\subsubsection{Teardown}
a42893dd
MW
843Details of initialization are necessarily class-specific, but typically it
844involves setting the instance's slots to appropriate values, and possibly
845linking it into some larger data structure to keep track of it.
846
847Teardown is performed by sending the instance the @|teardown| message,
848defined by the @|SodObject| class. The message returns an integer, used as a
849boolean flag. If the message returns zero, then the instance's storage
850should be deallocated. If the message returns nonzero, then it is safe for
851the caller to forget about instance, but should not deallocate its storage.
852This is \emph{not} an error return: if some teardown method fails then the
853program may be in an inconsistent state and should not continue.
d24d47f5 854
a42893dd
MW
855This simple protocol can be used, for example, to implement a reference
856counting system, as follows.
d24d47f5 857\begin{prog}
020b9e2b
MW
858 [nick = ref] \\
859 class ReferenceCountedObject \{ \\ \ind
860 unsigned nref = 1; \\-
861 void inc() \{ me@->ref.nref++; \} \\-
862 [role = around] \\
863 int obj.teardown() \\
864 \{ \\ \ind
865 if (--\,--me@->ref.nref) return (1); \\
866 else return (CALL_NEXT_METHOD); \-\\
867 \} \-\\
d24d47f5
MW
868 \}
869\end{prog}
870
a42893dd
MW
871This message uses a nonstandard method combination which works like the
872standard combination, except that the \emph{default behaviour}, if there is
873no overriding method, is to execute the superclass's teardown fragments, and
874to return zero. This default behaviour may be invoked multiple times if some
875method calls on its @|next_method| more than once, unless some other method
876takes steps to prevent this.
877
878A class can define \emph{teardown fragments}: pieces of literal code to be
879executed to shut down an instance. Each superclass's teardown fragments are
880executed with @|me| bound to an instance pointer of the appropriate
881superclass type; fragments defined by a more specific superclass are executed
882before fragments defined by a more specific superclass. A class may define
883more than one teardown fragment: the fragments are executed in the order in
884which they appear in the class definition. It is possible for an
885initialization fragment to use @|return| or @|goto| for special control-flow
886effects, but this is not likely to be a good idea. Similarly, it's probably
887a better idea to use an @|around| method to influence the return value than
888to write an explicit @|return| statement in a teardown fragment.
889
d24d47f5
MW
890\subsubsection{Deallocation}
891The details of instance deallocation are obviously specific to the allocation
892strategy used by the instance, and this is often orthogonal from the object's
893class.
894
895The code which makes the decision to destroy an object may often not be aware
896of the object's direct class. Low-level details of deallocation often
897require the proper base address of the instance's storage, which can be
898determined using the \descref{SOD_INSTBASE}[macro]{mac}.
899
3cc520db
MW
900%%%--------------------------------------------------------------------------
901\section{Metaclasses} \label{sec:concepts.metaclasses}
1f7d590d 902
caa6f4b9
MW
903%%%--------------------------------------------------------------------------
904\section{Compatibility considerations} \label{sec:concepts.compatibility}
905
906Sod doesn't make source-level compatibility especially difficult. As long as
907classes, slots, and messages don't change names or dissappear, and slots and
908messages retain their approximate types, everything will be fine.
909
910Binary compatibility is much more difficult. Unfortunately, Sod classes have
911rather fragile binary interfaces.\footnote{%
912 Research suggestion: investigate alternative instance and vtable layouts
913 which improve binary compatibility, probably at the expense of instance
914 compactness, and efficiency of slot access and message sending. There may
915 be interesting trade-offs to be made.} %
916
917If instances are allocated [FIXME]
918
1f7d590d
MW
919%%%----- That's all, folks --------------------------------------------------
920
921%%% Local variables:
922%%% mode: LaTeX
923%%% TeX-master: "sod.tex"
924%%% TeX-PDF-mode: t
925%%% End: