Replace the `init' class-slot function with an `init' message.
[sod] / doc / concepts.tex
index b8637e8..39cccb8 100644 (file)
@@ -195,7 +195,7 @@ It works as follows.
   earliest position in these candidate merges at which they disagree.  The
   \emph{candidate classes} at this position are the classes appearing at this
   position in the candidate merges.  Each candidate class must be a
-  superclass of exactly one of $C$'s direct superclasses, since otherwise the
+  superclass of distinct direct superclasses of $C$, since otherwise the
   candidates would be ordered by their common subclass's class precedence
   list.  The class precedence list contains, at this position, that candidate
   class whose subclass appears earliest in $C$'s local precedence order.
@@ -208,8 +208,8 @@ a link superclass, and the link superclass of a class $C$, if it exists, need
 not be a direct superclass of $C$.
 
 Superclass links must obey the following rule: if $C$ is a class, then there
-must be no three superclasses $X$, $Y$ and~$Z$ of $C$ such that both $Z$ is
-the link superclass of both $X$ and $Y$.  As a consequence of this rule, the
+must be no three superclasses $X$, $Y$ and~$Z$ of $C$ such that $Z$ is the
+link superclass of both $X$ and $Y$.  As a consequence of this rule, the
 superclasses of $C$ can be partitioned into linear \emph{chains}, such that
 superclasses $A$ and $B$ are in the same chain if and only if one can trace a
 path from $A$ to $B$ by following superclass links, or \emph{vice versa}.
@@ -246,12 +246,12 @@ qualified by the defining class's nickname.
 As well as defining slot names and types, a class can also associate an
 \emph{initial value} with each slot defined by itself or one of its
 subclasses.  A class $C$ provides an \emph{initialization function} (see
-\xref{sec:concepts.classes.c}, and \xref{sec:structures.root.sodclass}) which
-sets the slots of a \emph{direct} instance of the class to the correct
+\xref{sec:concepts.lifecycle.birth}, and \xref{sec:structures.root.sodclass})
+which sets the slots of a \emph{direct} instance of the class to the correct
 initial values.  If several of $C$'s superclasses define initializers for the
 same slot then the initializer from the most specific such class is used.  If
 none of $C$'s superclasses define an initializer for some slot then that slot
-will not be initialized.
+will be left uninitialized.
 
 The initializer for a slot with scalar type may be any C expression.  The
 initializer for a slot with aggregate type must contain only constant
@@ -307,88 +307,6 @@ functions for working with that class's instances.  (The @|SodClass| class
 doesn't define any messages, so it doesn't have any methods.  In Sod, a class
 slot containing a function pointer is not at all the same thing as a method.)
 
-\subsubsection{Instance allocation, imprinting, and initialization}
-It is in general not sufficient to declare (or @|malloc|) an object of the
-appropriate class type and fill it in, since the class type only describes an
-instance's layout from the point of view of a single superclass chain.  The
-correct type to allocate, to store a direct instance of some class is a
-structure whose tag is the class name suffixed with `@|__ilayout|'; e.g., the
-correct layout structure for a direct instance of @|MyClass| would be
-@|struct MyClass__ilayout|.
-
-Instance layouts may be declared as objects with automatic storage duration
-(colloquially, `allocated on the stack') or allocated dynamically, e.g.,
-using @|malloc|.  Sod's runtime system doesn't retain addresses of instances,
-so, for example, Sod doesn't make using a fancy allocator which sometimes
-moves objects around in memory any more difficult than it needs to be.
-
-Once storage for an instance has been allocated, it must be \emph{imprinted}
-before it can be used.  Imprinting an instance stores some metadata about its
-direct class in the instance structure, so that the rest of the program (and
-Sod's runtime library) can tell what sort of object it is, and how to use
-it.\footnote{%
-  Specifically, imprinting an instance's storage involves storing the
-  appropriate vtable pointers in the right places in it.} %
-A class object's @|imprint| slot points to a function which will correctly
-imprint storage for one of that class's instances.
-
-Once an instance's storage has been imprinted, it is possible to send the
-instance messages; however, the instance's slots are uninitialized at this
-point, so most methods are unlikely to do much of any use.  So, usually, you
-don't just want to imprint instance storage, but to \emph{initialize} an
-instance.  Initialization includes imprinting, but also sets the new
-instance's slots to their initial values, as defined by the class.  If
-neither the class nor any of its superclasses defines an initializer for a
-slot then it will not be initialized.
-
-There is currently no facility for providing parameters to the instance
-initialization process (e.g., for use by slot initializer expressions).
-Instance initialization is a complicated matter and for now I want to
-experiment with various approaches before committing to one.  My current
-interim approach is to specify slot initializers where appropriate and send
-class-specific messages for more complicated parametrized initialization.
-
-Automatic-duration instances can be conveniently constructed and initialized
-using the @|SOD_DECL| macro (page~\pageref{mac:SOD-DECL}).  No special
-support is currently provided for dynamically allocated instances.  A simple
-function using @|malloc| might work as follows.
-\begin{prog}
-  void *new_instance(const SodClass *c) \\
-  \{ \\ \ind
-    void *p = malloc(c@->cls.initsz); \\
-    if (!p) return (0); \\
-    c@->cls.init(p); \\
-    return (p); \- \\
-  \}
-\end{prog}
-
-\subsubsection{Instance finalization and deallocation}
-There is currently no provided assistance for finalization or deallocation.
-It is the programmer's responsibility to decide and implement an appropriate
-protocol.  Note that to free an instance allocated from the heap, one must
-correctly find its base address: the @|SOD_INSTBASE| macro
-(page~\pageref{mac:SOD-INSTBASE}) will do this for you.
-
-The following simple mixin class is suggested.
-\begin{prog}
-  [nick = disposable] \\*
-  class DisposableObject : SodObject \{ \\*[\jot] \ind
-    void release() \{ ; \} \\*
-    \quad /\=\+* Release resources held by the receiver. */ \-\- \\*[\jot]
-  \} \\[\bigskipamount]
-  code c : user \{ \\* \ind
-    /\=\+* Free object p's instance storage.  If p is a DisposableObject \\*
-       {}* then release its resources beforehand. \\*
-       {}*/ \- \\*
-    void free_instance(void *p) \\*
-    \{ \\* \ind
-      DisposableObject *d = SOD_CONVERT(DisposableObject, p); \\*
-      if (d) DisposableObject_release(d); \\*
-      free(d); \- \\*
-    \} \- \\*
-  \}
-\end{prog}
-
 \subsubsection{Conversions}
 Suppose one has a value of type pointer to class type of some class~$C$, and
 wants to convert it to a pointer to class type of some other class~$B$.
@@ -406,13 +324,14 @@ There are three main cases to distinguish.
   a lookup at runtime to find the appropriate offset by which to adjust the
   pointer.  The conversion can be performed using the appropriate generated
   upcast macro (see below); the general case is handled by the macro
-  @|SOD_XCHAIN| (page~\pageref{mac:SOD-XCHAIN}).
+  \descref{SOD_XCHAIN}{mac}.
 \item If $B$ is a subclass of~$C$ then the conversion is an \emph{upcast};
   otherwise the conversion is a~\emph{cross-cast}.  In either case, the
   conversion can fail: the object in question might not be an instance of~$B$
-  at all.  The macro @|SOD_CONVERT| (page~\pageref{mac:SOD-CONVERT}) and the
-  function @|sod_convert| (page~\pageref{fun:sod-convert}) perform general
-  conversions.  They return a null pointer if the conversion fails.
+  at all.  The macro \descref{SOD_CONVERT}{mac} and the function
+  \descref{sod_convert}{fun} perform general conversions.  They return a null
+  pointer if the conversion fails.  (There are therefore your analogue to the
+  \Cplusplus @|dynamic_cast<>| operator.)
 \end{itemize}
 The Sod translator generates macros for performing both in-chain and
 cross-chain upcasts.  For each class~$C$, and each proper superclass~$B$
@@ -431,6 +350,48 @@ nickname @|super|, then the macro @|MYCLASS__CONV_SUPER| converts a
 \xref{sec:structures.layout.additional} for the formal description.
 
 %%%--------------------------------------------------------------------------
+\section{Keyword arguments} \label{sec:concepts.keywords}
+
+In standard C, the actual arguments provided to a function are matched up
+with the formal arguments given in the function definition according to their
+ordering in a list.  Unless the (rather cumbersome) machinery for dealing
+with variable-length argument tails (@|<stdarg.h>|) is used, exactly the
+correct number of arguments must be supplied, and in the correct order.
+
+A \emph{keyword argument} is matched by its distinctive \emph{name}, rather
+than by its position in a list.  Keyword arguments may be \emph{omitted},
+causing some default behaviour by the function.  A function can detect
+whether a particular keyword argument was supplied: so the default behaviour
+need not be the same as that caused by any specific value of the argument.
+
+Keyword arguments can be provided in three ways.
+\begin{enumerate}
+\item Directly, as a variable-length argument tail, consisting (for the most
+  part) of alternating keyword names, as pointers to null-terminated strings,
+  and argument values, and terminated by a null pointer.  This is somewhat
+  error-prone, and the support library defines some macros which help ensure
+  that keyword argument lists are well formed.
+\item Indirectly, through a @|va_list| object capturing a variable-length
+  argument tail passed to some other function.  Such indirect argument tails
+  have the same structure as the direct argument tails described above.
+  Because @|va_list| objects are hard to copy, the keyword-argument support
+  library consistently passes @|va_list| objects \emph{by reference}
+  throughout its programming interface.
+\item Indirectly, through a vector of @|struct kwval| objects, each of which
+  contains a keyword name, as a pointer to a null-terminated string, and the
+  \emph{address} of a corresponding argument value.  (This indirection is
+  necessary so that the items in the vector can be of uniform size.)
+  Argument vectors are rather inconvenient to use, but are the only practical
+  way in which a caller can decide at runtime which arguments to include in a
+  call, which is useful when writing wrapper functions.
+\end{enumerate}
+
+Keyword arguments are provided as a general feature for C functions.
+However, Sod has special support for messages which accept keyword arguments
+(\xref{sec:concepts.methods.keywords}); and they play an essential role in
+the instance construction protocol (\xref{sec:concepts.lifecycle.birth}).
+
+%%%--------------------------------------------------------------------------
 \section{Messages and methods} \label{sec:concepts.methods}
 
 Objects can be sent \emph{messages}.  A message has a \emph{name}, and
@@ -495,13 +456,11 @@ another, $N$, with respect to a receiving class~$C$, if the class defining
 $M$ is a more (resp.\ less) specific superclass of~$C$ than the class
 defining $N$.
 
-\subsection{The standard method combination}
-\label{sec:concepts.methods.standard}
-
+\subsubsection{The standard method combination}
 The default method combination is called the \emph{standard method
 combination}; other method combinations are useful occasionally for special
 effects.  The standard method combination accepts four direct method roles,
-called @|primary| (the default), @|before|, @|after|, and @|around|.
+called `primary' (the default), @|before|, @|after|, and @|around|.
 
 All direct methods subject to the standard method combination must have
 argument lists which \emph{match} the message's argument list:
@@ -536,10 +495,13 @@ follows.
   returns; otherwise the behaviour of @|next_method| is to invoke the before
   methods (if any), followed by the most specific primary method, followed by
   the @|around| methods (if any), and to return whichever value was returned
-  by the most specific primary method.  That is, the behaviour of the least
-  specific @|around| method's @|next_method| function is exactly the
-  behaviour that the effective method would have if there were no @|around|
-  methods.
+  by the most specific primary method, as described in the following items.
+  That is, the behaviour of the least specific @|around| method's
+  @|next_method| function is exactly the behaviour that the effective method
+  would have if there were no @|around| methods.  Note that if the
+  least-specific @|around| method calls its @|next_method| more than once
+  then the whole sequence of @|before|, primary, and @|after| methods occurs
+  multiple times.
 
   The value returned by the most specific @|around| method is the value
   returned by the effective method.
@@ -575,7 +537,7 @@ A typical use for @|around| methods is to allow a base class to set up the
 dynamic environment appropriately for the primary methods of its subclasses,
 e.g., by claiming a lock, and restore it afterwards.
 
-The @|next_method| function provided to methods with the @|primary| and
+The @|next_method| function provided to methods with the primary and
 @|around| roles accepts the same arguments, and returns the same type, as the
 message, except that one or two additional arguments are inserted at the
 front of the argument list.  The first additional argument is always the
@@ -586,7 +548,7 @@ second additional argument; otherwise, In the former case, a variable
 of the argument pointer (so the method body can process the variable argument
 suffix itself, and still pass a fresh copy on to the next method).
 
-A method with the @|primary| or @|around| role may use the convenience macro
+A method with the primary or @|around| role may use the convenience macro
 @|CALL_NEXT_METHOD|, which takes no arguments itself, and simply calls
 @|next_method| with appropriate arguments: the receiver @|me| pointer, the
 argument pointer @|sod__master_ap| (if applicable), and the method's
@@ -594,9 +556,12 @@ arguments.  If the method body has overwritten its formal arguments, then
 @|CALL_NEXT_METHOD| will pass along the updated values, rather than the
 original ones.
 
-\subsection{Aggregating method combinations}
-\label{sec:concepts.methods.aggregating}
+A primary or @|around| method which invokes its @|next_method| function is
+said to \emph{extend} the message behaviour; a method which does not invoke
+its @|next_method| is said to \emph{override} the behaviour.  Note that a
+method may make a decision to override or extend at runtime.
 
+\subsubsection{Aggregating method combinations}
 A number of other method combinations are provided.  They are called
 `aggregating' method combinations because, instead of invoking just the most
 specific primary method, as the standard method combination does, they invoke
@@ -639,6 +604,228 @@ The aggregating method combinations provided are as follows.
 There is also a @|custom| aggregating method combination, which is described
 in \xref{sec:fixme.custom-aggregating-method-combination}.
 
+
+\subsection{Messages with keyword arguments}
+\label{sec:concepts.methods.keywords}
+
+A message or a direct method may declare that it accepts keyword arguments.
+A message which accepts keyword arguments is called a \emph{keyword message};
+a direct method which accepts keyword arguments is called a \emph{keyword
+method}.
+
+While method combinations may set their own rules, usually keyword methods
+can only be defined on keyword messages, and all methods defined on a keyword
+message must be keyword methods.  The direct methods defined on a keyword
+message may differ in the keywords they accept, both from each other, and
+from the message.  If two superclasses of some common class both define
+keyword methods on the same message, and the methods both accept a keyword
+argument with the same name, then these two keyword arguments must also have
+the same type.  Different applicable methods may declare keyword arguments
+with the same name but different defaults; see below.
+
+The keyword arguments acceptable in a message sent to an object are the
+keywords listed in the message definition, together with all of the keywords
+accepted by any applicable method.  There is no easy way to determine at
+runtime whether a particular keyword is acceptable in a message to a given
+instance.
+
+At runtime, a direct method which accepts one or more keyword arguments
+receives an additional argument named @|suppliedp|.  This argument is a small
+structure.  For each keyword argument named $k$ accepted by the direct
+method, @|suppliedp| contains a one-bit-wide bitfield member of type
+@|unsigned|, also named $k$.  If a keyword argument named $k$ was passed in
+the message, then @|suppliedp.$k$| is one, and $k$ contains the argument
+value; otherwise @|suppliedp.$k$| is zero, and $k$ contains the default value
+from the direct method definition if there was one, or an unspecified value
+otherwise.
+
+%%%--------------------------------------------------------------------------
+\section{The object lifecycle} \label{sec:concepts.lifecycle}
+
+\subsection{Creation} \label{sec:concepts.lifecycle.birth}
+
+Construction of a new instance of a class involves three steps.
+\begin{enumerate}
+\item \emph{Allocation} arranges for there to be storage space for the
+  instance's slots and associated metadata.
+\item \emph{Imprinting} fills in the instance's metadata, associating the
+  instance with its class.
+\item \emph{Initialization} stores appropriate initial values in the
+  instance's slots, and maybe links it into any external data structures as
+  necessary.
+\end{enumerate}
+The \descref{SOD_DECL}[macro]{mac} handles constructing instances with
+automatic storage duration (`on the stack').  Programmers can add support for
+other allocation strategies by using the \descref{SOD_INIT}[macro]{mac} and
+the \descref{sod_init}{fun} and \descref{sod_initv}{fun} functions, which
+package up imprinting and initialization.
+
+\subsubsection{Allocation}
+Instances of most classes (specifically including those classes defined by
+Sod itself) can be held in any storage of sufficient size.  The in-memory
+layout of an instance of some class~$C$ is described by the type @|struct
+$C$__ilayout|, and if the relevant class is known at compile time then the
+best way to discover the layout size is with the @|sizeof| operator.  Failing
+that, the size required to hold an instance of $C$ is available in a slot in
+$C$'s class object, as @|$C$__class@->cls.initsz|.
+
+It is not in general sufficient to declare, or otherwise allocate, an object
+of the class type $C$.  The class type only describes a single chain of the
+object's layout.  It is nearly always an error to use the class type as if it
+is a \emph{complete type}, e.g., to declare objects or arrays of the class
+type, or to enquire about its size or alignment requirements.
+
+Instance layouts may be declared as objects with automatic storage duration
+(colloquially, `allocated on the stack') or allocated dynamically, e.g.,
+using @|malloc|.  They may be included as members of structures or unions, or
+elements of arrays.  Sod's runtime system doesn't retain addresses of
+instances, so, for example, Sod doesn't make using fancy allocators which
+sometimes move objects around in memory any more difficult than it needs to
+be.
+
+There isn't any way to discover the alignment required for a particular
+class's instances at runtime; it's best to be conservative and assume that
+the platform's strictest alignment requirement applies.
+
+The following simple function correctly allocates and returns space for an
+instance of a class given a pointer to its class object @<cls>.
+\begin{prog}
+  void *allocate_instance(const SodClass *cls) \\ \ind
+    \{ return malloc(cls@->cls.initsz); \}
+\end{prog}
+
+\subsubsection{Imprinting}
+Once storage has been allocated, it must be \emph{imprinted} before it can be
+used as an instance of a class, e.g., before any messages can be sent to it.
+
+Imprinting an instance stores some metadata about its direct class in the
+instance structure, so that the rest of the program (and Sod's runtime
+library) can tell what sort of object it is, and how to use it.\footnote{%
+  Specifically, imprinting an instance's storage involves storing the
+  appropriate vtable pointers in the right places in it.} %
+A class object's @|imprint| slot points to a function which will correctly
+imprint storage for one of that class's instances.
+
+Once an instance's storage has been imprinted, it is technically possible to
+send messages to the instance; however the instance's slots are still
+uninitialized at this point, the applicable methods are unlikely to do much
+of any use unless they've been written specifically for the purpose.
+
+The following simple function imprints storage at address @<p> as an instance
+of a class, given a pointer to its class object @<cls>.
+\begin{prog}
+  void imprint_instance(const SodClass *cls, void *p) \\ \ind
+    \{ cls@->cls.imprint(p); \}
+\end{prog}
+
+\subsubsection{Initialization}
+The final step for constructing a new instance is to \emph{initialize} it, to
+establish the necessary invariants for the instance itself and the
+environment in which it operates.
+
+Details of initialization are necessarily class-specific, but typically it
+involves setting the instance's slots to appropriate values, and possibly
+linking it into some larger data structure to keep track of it.
+
+Initialization is performed by sending the imprinted instance an @|init|
+message, defined by the @|SodObject| class.  This message uses a nonstandard
+method combination which works like the standard combination, except that the
+\emph{default behaviour}, if there is no overriding method, is to initialize
+the instance's slots using the initializers defined in the class and its
+superclasses.  This default behaviour may be invoked multiple times if some
+method calls on its @|next_method| more than once, unless some other method
+takes steps to prevent this.
+
+The recommended way to add new initialization behaviour is to define @|after|
+methods on the @|init| message.  These will be run after the slot
+initializers have been applied, in reverse precedence order.
+
+Initialization is \emph{parametrized}, so the caller may select from a space
+of possible initial states for the new instance, or to inform the new
+instance about some other objects known to the caller.  Specifically, the
+@|init| message accepts keyword arguments (\xref{sec:concepts.keywords})
+which can be defined and used by methods defined on it.
+
+\subsubsection{Example}
+The following is a simple function, with syntactic-sugar macro, which
+allocate storage for an instance of a class, imprints and initializes it, and
+returns a pointer to the new instance.
+\begin{prog}
+  void *make_instance(const SodClass *c, @|\dots|) \\
+  \{ \\ \ind
+    va_list ap;
+    void *p = malloc(c@->cls.initsz); \\
+    if (!p) return (0); \\
+    va_start(ap, c); \\
+    sod_initv(c, p, ap); \\
+    va_end(ap); \\
+    return (p); \- \\
+  \}
+  \\+
+  \#define MAKE(cls, keys) (cls *)make_instance(cls\#\#__class, keys)
+\end{prog}
+
+
+\subsection{Destruction}
+\label{sec:concepts.lifecycle.death}
+
+Destruction of an instance, when it is no longer required, consists of two
+steps.
+\begin{enumerate}
+\item \emph{Teardown} releases any resources held by the instance and
+  disentangles it from any external data structures.
+\item \emph{Deallocation} releases the memory used to store the instance so
+  that it can be reused.
+\end{enumerate}
+
+\subsubsection{Teardown}
+Details of teardown are class-specific, but typically it involves releasing
+resources held by the instance, and possibly unlinking it from some larger
+data structure which used to keep track of it.
+
+There is no provided protocol for teardown: classes whose instances require
+teardown behaviour must define and implement an appropriate protocol of their
+own.  The following class may serve for simple cases.
+\begin{prog}
+  [nick = disposable] \\
+  class DisposableObject : SodObject \{ \\- \ind
+    void release() \{ ; \} \\
+    \quad /* Release resources held by the receiver. */ \- \\-
+  \}
+  \\+
+  code c : user \{ \\- \ind
+    /* If p is a a DisposableObject then release its resources. */ \\
+    void maybe_dispose(void *p) \\
+    \{ \\ \ind
+      DisposableObject *d = SOD_CONVERT(DisposableObject, p); \\
+      if (d) DisposableObject_release(d); \- \\
+    \} \- \\
+  \}
+\end{prog}
+
+\subsubsection{Deallocation}
+The details of instance deallocation are obviously specific to the allocation
+strategy used by the instance, and this is often orthogonal from the object's
+class.
+
+The code which makes the decision to destroy an object may often not be aware
+of the object's direct class.  Low-level details of deallocation often
+require the proper base address of the instance's storage, which can be
+determined using the \descref{SOD_INSTBASE}[macro]{mac}.
+
+\subsubsection{Example}
+The following is a counterpart to the @|new_instance| function
+(\xref{sec:concepts.lifecycle.birth}), which tears down and deallocates an
+instance allocated using @|malloc|.
+\begin{prog}
+  void free_instance(void *p) \\
+  \{ \\ \ind
+    SodObject *obj = p; \\
+    maybe_dispose(p); \\
+    free(SOD_INSTBASE(obj)); \- \\
+  \}
+\end{prog}
+
 %%%--------------------------------------------------------------------------
 \section{Metaclasses} \label{sec:concepts.metaclasses}