chiark / gitweb /
lib/: Pure C machinery for handling `keyword arguments' to functions.
[sod] / doc / runtime.tex
CommitLineData
62f9852b
MW
1%%% -*-latex-*-
2%%%
3%%% The runtime library
4%%%
5%%% (c) 2015 Straylight/Edgeware
6%%%
7
8%%%----- Licensing notice ---------------------------------------------------
9%%%
10%%% This file is part of the Simple Object Definition system.
11%%%
12%%% SOD is free software; you can redistribute it and/or modify
13%%% it under the terms of the GNU General Public License as published by
14%%% the Free Software Foundation; either version 2 of the License, or
15%%% (at your option) any later version.
16%%%
17%%% SOD is distributed in the hope that it will be useful,
18%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
19%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20%%% GNU General Public License for more details.
21%%%
22%%% You should have received a copy of the GNU General Public License
23%%% along with SOD; if not, write to the Free Software Foundation,
24%%% Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25
26\chapter{The runtime library} \label{ch:runtime}
27
e520bc24
MW
28This chapter describes the runtime support macros and functions provided by
29the Sod library. The common structure of object instances and classes is
30described in \xref{ch:structures}.
31
32%%%--------------------------------------------------------------------------
9e91c8e7
MW
33\section{Keyword argument support} \label{sec:runtime.keywords}
34
35This section describes the types, macros, and functions exposed in the
36@|<sod/keyword.h>| header file which provides support for defining and
37calling functions which make use of keyword arguments; see \xref{sec:concepts.keywords}.
38
39
40\subsection{Type definitions} \label{sec:sec:runtime.keywords.types}
41
42The header file defines two simple structure types, and a function type which
43will be described later.
44
45\begin{describe}[struct kwval]{type}
46 {struct kwval \{ \\ \ind
47 const char *kw; \\
48 const void *val; \- \\
49 \};}
50
51 The @|kwval| structure describes a keyword argument name/value pair. The
52 @|kw| member points to the name, as a null-terminated string. The @|val|
53 member always contains the \emph{address} of the value. (This somewhat
54 inconvenient arrangement makes the size of a @|kwval| object independent of
55 the actual argument type.)
56\end{describe}
57
58\begin{describe}[struct kwtab]{type}
59 {struct kwtab \{ \\ \ind
60 const struct kwval *v; \\
61 size_t n; \- \\
62 \};}
63
64 The @|kwtab| structure describes a list of keyword arguments, represented
65 as a vector of @|kwval| structures. The @|v| member points to the start of
66 the vector; the @|n| member contains the number of elements in the vector.
67\end{describe}
68
69
70\subsection{Calling functions with keyword arguments}
71\label{sec:runtime.keywords.calling}
72
73Functions which accept keyword arguments are ordinary C functions with
74variable-length argument tails. Hence, they can be called using ordinary C
75(of the right kind) and all will be well. However, argument lists must
76follow certain rules (which will be described in full below); failure to do
77this will result in \emph{undefined behaviour}.
78
79The header file provides integration with some C compilers in the form of
80macros which can be used to help the compiler diagnose errors in calls to
81keyword-accepting functions; but such support is rather limited at the
82moment. Some additional macros are provided for use in calls to such
83functions, and it is recommended that, where possible, these are used. In
84particular, it's all too easy to forget the trailing null terminator which
85marks the end of a list of keyword arguments.
86
87That said, the underlying machinery is presented first, and the convenience
88macros are described later.
89
90\subsubsection{Keyword argument mechanism}
91The argument tail, following the mandatory arguments, consists of a sequence
92of zero or more alternating keyword names, as pointers to null-terminated
93strings (with type @|const char~*|), and their argument values. This
94sequence is finally terminated by a null pointer (again with type @|const
95char~*|) in place of a keyword name.
96
97Each function may define for itself which keyword names it accepts,
98and what types the corresponding argument values should have.
99There are also (currently) three special keyword names.
100\begin{description} \let\makelabel\code
101
102\item[kw.valist] This special keyword is followed by a pointer to a
103 variable-length argument tail cursor object, of type @|va_list~*|. This
104 cursor object will be modified as the function extracts successive
105 arguments from the tail. The argument tail should consist of alternating
106 keyword names and argument values, as described above, including the first
107 keyword name. (This is therefore different from the convention used when
108 calling keyword argument parser functions: see the description of the
109 \descref{KWSET_PARSEFN}[macro]{mac} for more details about these.) The
110 argument tail may itself contain the special keywords.
111
112\item[kw.tab] This special keyword is followed by \emph{two} argument values:
113 a pointer to the base of a vector of @|kwval| structures, and the number of
114 elements in this vector (as a @|size_t|). Each element of the vector
115 describes a single keyword argument: the @|kw| member points to the
116 keyword's name, and the @|val| member points to the value.
117
118 The vector may contain special keywords. The @|val| pointer for a
119 @|kw.valist| argument should contain the address of an object of type
120 @|va_list~*| (and not point directly to the cursor object, since @|val| is
121 has type @|const void~*| but the cursor will be modified as its argument
122 tail is traversed). The @|val| pointer for a @|kw.tab| argument should
123 contain the address of a @|kwtab| structure which itself contains the base
124 address and length of the argument vector to be processed.
125
126\item[kw.unknown] This keyword is never accepted by any function. If it is
127 encountered, the @|kw_unknown| function is called to report the situation
128 as an error; see below.
129
130\end{description}
131It is possible to construct a circular structure of indirect argument lists
132(in a number of ways). Don't try to pass such a structure to a function: the
133result will be unbounded recursion or some other bad outcome.
134
135\subsubsection{Argument list structuring macros}
136The following macros are intended to help with constructing keyword argument
137lists. Their use is not essential, but may help prevent errors.
138
139\begin{describe}[KWARGS]{mac}{KWARGS(@<body>)}
140 The @<body> encloses a sequence of keyword arguments expressed as calls to
141 argument consists of a sequence of calls to the keyword-argument macros
142 described below, one after another without any separation.
143
144 In C89, macro actual arguments are not permitted to be empty; if there are
145 no keyword arguments to provide, and you're using a C89 compiler, then use
146 @|NO_KWARGS| (below) instead. If your compiler supports C99 or later, it's
147 fine to just write @|KWARGS()| instead.
148\end{describe}
149
150\begin{describe}{mac}{NO_KWARGS}
151 A marker, to be written instead of a @|KWARGS| invocation, to indicate that
152 no keyword arguments are to be passed to a function.
153
154 This is unnecessary with compilers which support C99 or later, since once
155 can use @|KWARGS()| with an empty @<body> argument.
156\end{describe}
157
158The following keyword-argument macros can be used within the @|KWARGS|
159@<body> argument.
160
161\begin{describe}[K]{mac}{K(@<name>, @<value>)}
162 Passes a keyword @<name> and its corresponding @<value>, as a pair of
163 arguments. The @<name> should be a single identifier (not a quoted
164 string). The @<value> may be any C expression of the appropriate type.
165\end{describe}
166
167\begin{describe}[K_VALIST]{mac}{K_VALIST(@<ap>)}
168 Passes an indirect variable-length argument tail. The argument @<ap>
169 should be an lvalue of type @|va_list|, which will be passed by reference.
170\end{describe}
171
172\begin{describe}[K_TAB]{mac}{K_TAB(@<v>, @<n>)}
173 Passes a vector of keyword arguments. The argument @<v> should be the base
174 address of the vector, and @<n> should be the number of elements in the
175 vector.
176\end{describe}
177
178
179\subsection{Defining functions with keyword arguments}
180\label{sec:runtime.keywords.defining}
181
182\subsubsection{Keyword sets}
183A \emph{keyword set} defines the collection of keyword arguments accepted by
184a particular function. The same keyword set may be used by several
185functions. (If your function currently accepts no keyword arguments, but you
186plan to add some later, do not define a keyword set, and use the
187@|KWPARSE_EMPTY| macro described below.)
188
189Each keyword set has a name, which is a C identifier. It's good to choose
190meaningful and distinctive names for keyword sets. Keyword set names are
191meaningful at runtime: they are used as part of the @|kw_unknown| protocol
192(\xref{sec:runtime.keywords.unknown}), and may be examined by handler
193functions, or reported to a user in error messages. For a keyword set which
194is used only by a single function, it is recommended that the set be given
195the same name as the function.
196
197The keyword arguments for a keyword set named @<set> are described by a `list
198macro' named @|@<set>{}_KWSET|. This macro takes a single argument,
199conventionally named @`_'.
200
201It should expand to a sequence of one or more list items of the form
202\begin{prog}
203 _(@<type>, @<name>, @<default>)
204\end{prog}
205with no separation between them.
206
207For example:
208\begin{prog}
209 \#define example_KWSET(_) @\\ \\ \ind
210 _(int, x, 0) @\\ \\
211 _(const char *, y, NULL)
212\end{prog}
213
214Each @<name> should be a distinct C identifier; they will be used to name
215structure members. An argument @<name> should not end with the suffix
216@`_suppliedp' (for reasons which will soon become apparent).
217
218Each @<type> should be a C @<type-name> such that
219\begin{prog}
220 @<type> @<name> ;
221\end{prog}
222is a valid declaration: so it may consist of declaration specifiers and
223(possibly qualified) pointer declarator markers, but not array or function
224markers (since they would have to be placed after the @<name>). This is the
225same requirement made by the standard \man{va_arg}{3} macro.
226
227Each @<default> should be an initializer expression or brace-enclosed list,
228suitable for use in an aggregate initializer for a variable with automatic
229storage duration. (In C89, aggregate initializers may contain only constant
230expressions; this restriction was lifted in C99.)
231
232\subsubsection{Function declaration markers}
233The following marker macros are intended to be used in both declarations and
234definitions of functions which accept keyword arguments.
235
236\begin{describe}{mac}{KWTAIL}
237 The @|KWTAIL| is expected to be used at the end of function parameter type
238 list to indicate that the function accepts keyword arguments; if there are
239 preceding mandatory arguments then the @|KWTAIL| marker should be separated
240 from them with a comma @`,'. (It is permitted for a function parameter
241 type list to contain only a @|KWTAIL| marker.)
242
243 Specifically, the macro declares a mandatory argument @|const char
244 *kwfirst_| (to collect the first keyword name), and a variable-length
245 argument tail.
246
247 The \descref{KWPARSE}[macro]{mac} assumes that the enclosing function's
248 argument list ends with a @|KWTAIL| marker.
249\end{describe}
250
251\begin{describe}{mac}{KWCALL}
252 The @|KWCALL| macro acts as a declaration specifier for functions which
253 accept keyword arguments. Its effect is to arrange for the compiler to
254 check, as far as is possible, that calls to the function are well-formed
255 according to the keyword-argument rules. The exact checking performed
256 depends on the compiler's abilities (and how well supported the compiler
257 is): it may check that every other argument is a string; it may check that
258 the list is terminated with a null pointer; it may not do anything at all.
259 Again, this marker should be included in a function's definition and in any
260 declarations.
261\end{describe}
262
263\subsubsection{Auxiliary definitions}
264The following macros define data types and functions used for collecting
265keyword arguments.
266
267\begin{describe}[KWSET_STRUCT]{mac}{KWSET_STRUCT(@<set>);}
268 The @|KWSET_STRUCT| macro defines a \emph{keyword structure} named @|struct
269 @<set>{}_kwargs|. For each argument defined in the keyword set, this
270 structure contains two members: one has exactly the @<name> and @<type>
271 listed in the keyword set definition; the other is a 1-bit-wide bitfield of
272 type @|unsigned int| named @|@<name>{}_suppliedp|.
273\end{describe}
274
275\begin{describe}[KWDECL]{mac}
276 {@<declaration-specifiers> KWDECL(@<set>, @<kw>);}
277 The macro declares and initializes a keyword argument structure variable
278 named @<kw> for the named keyword @<set>. The optional
279 @<declaration-specifiers> may provide additional storage-class, qualifiers,
280 or other declaration specifiers. The @`_suppliedp' flags are initialized
281 to zero; the other members are initialized with the corresponding defaults
282 from the keyword-set definition.
283\end{describe}
284
285\begin{describe}[KWSET_PARSEFN]{mac}
286 {@<declaration-specifiers> KWSET_PARSEFN(@<set>)}
287
288 The macro @|KWSET_PARSEFN| defines a keyword argument \emph{parser
289 function}
290 \begin{prog}
291 void @<set>{}_kwparse(\=struct @<set>{}_kwargs *@<kw>,
292 const char *@<kwfirst>, va_list *@<ap>, \+ \\
293 const struct kwval *@<v>, size_t @<n>);
294 \end{prog}
295 The macro call can (and usually will) be preceded by storage class
296 specifiers such as @|static|, for example to adjust the linkage of the
297 name.\footnote{%
298 I don't recommend declaring parser functions @|inline|: parser functions
299 are somewhat large, and modern compilers are pretty good at figuring out
300 whether to inline static functions.} %
301
302 The function's behaviour is as follows. It parses keyword arguments from a
303 variable-length argument tail, and/or a vector of @|kwval| structures.
304 When a keyword argument is recognized, for some keyword @<name>, the
305 keyword argument structure pointed to by @<kw> is updated: the flag
306 @|@<name>{}_suppliedp| is set to 1; and the argument value is stored (by
307 simple assignment) in the @<name> member.
308
309 Hence, if the @`_suppliedp' members are initialized to zero, the caller can
310 determine which keyword arguments were supplied. It is not possible to
311 discover whether two or more arguments have the same keyword: in this case,
312 the value from the last such argument is left in the keyword argument
313 structure, and any values from earlier arguments are lost. (For this
314 purpose, the argument vector @<v> is scanned \emph{after} the
315 variable-length argument tail captured in @<ap>.)
316
317 The variable-argument tail is read from the list described by @|* @<ap>|.
318 The argument tail is expected to consist of alternating keyword strings (as
319 ordinary null-terminated strings) and the corresponding values, terminated
320 by a null pointer of type @|const char~*| in place of a keyword; except
321 that the first keyword (or terminating null pointer, if no arguments are
322 provided) is expected to have been extracted already and provided as the
323 @<kwfirst> argument; the first argument retrieved using the @|va_list|
324 cursor object should then be the value corresponding to the keyword named
325 by @<kwfirst>.\footnote{%
326 This slightly unusual convention makes it possible for a function to
327 collect the first keyword as a separate mandatory argument, which is
328 essential if there are no other mandatory arguments. It also means that
329 the compiler will emit a diagnostic if you attempt to call a function
330 which expects keyword arguments, but don't supply any and forget the null
331 pointer which terminates the (empty) list.} %
332 If @<kwfirst> is a null pointer, then @<ap> need not be a valid pointer;
333 otherwise, the cursor object @|* @<ap>| will be modified as the function
334 extracts successive arguments from the tail.
335
336 The keyword vector is read from the vector of @|kwval| structures starting
337 at address @<v> and containing the following @<n> items. If @<n> is zero
338 then @<v> need not be a valid pointer.
339
340 The function also handles the special @|kw.valist| and @|kw.tab| arguments
341 described above (\xref{sec:runtime.keywords.calling}). If an unrecognized
342 keyword argument is encountered, then \descref{kw_unknown}{fun} is called.
343\end{describe}
344
345\subsubsection{Parsing keywords}
346The following macros make use of the definitions described above to actually
347make a function's keyword arguments available to it.
348
349\begin{describe}[KW_PARSE]{mac}{KW_PARSE(@<set>, @<kw>, @<kwfirst>);}
350 The @|KW_PARSE| macro invokes a keyword argument parsing function. The
351 @<set> argument should name a keyword set; @<kw> should be an lvalue of
352 type @|struct @<set>{}_kwargs|; and @<kwfirst> should be the name of the
353 enclosing function's last mandatory argument, which must have type @|const
354 char~*|.
355
356 It calls the function @|@<set>{}_kwparse| with five arguments: the address
357 of the keyword argument structure @<kw>; the string pointer @<kwfirst>; the
358 address of a temporary argument-tail cursor object of type @|va_list|,
359 constructed on the assumption that @<kwfirst> is the enclosing function's
360 final keyword argument; a null pointer; and the value zero (signifying an
361 empty keyword-argument vector).
362
363 If the variable @<kw> was declared using \descref{KWDECL}{mac} and the
364 function @|@<set>{}_kwparse| has been defined using
365 \descref{KWSET_PARSEFN}{mac} then the effect is to parse the keyword
366 arguments passed to the function and set the members of @<kw>
367 appropriately.
368\end{describe}
369
370\begin{describe}[KWPARSE]{mac}{KWPARSE(@<set>);}
371 The macro @|KWPARSE| (note the lack of underscore) combines
372 \descref{KWDECL}{mac} and \descref{KW_PARSE}{mac}. It declares and
373 initializes a keyword argument structure variable with the fixed name
374 @|kw|, and parses the keyword arguments provided to the enclosing function,
375 storing the results in @|kw|. It assumes that the first keyword name is in
376 an argument named @|kwfirst_|, as set up by the
377 \descref{KWTAIL}[marker]{mac}.
378
379 The macro expands both to a variable declaration and a statement: in C89,
380 declarations must precede statements, so under C89 rules this macro must
381 appear exactly between the declarations at the head of a brace-enclosed
382 block (typically the function body) and the statements at the end. This
383 restriction was lifted in C99, so the macro may appear anywhere in the
384 function body. However, it is recommended that callers avoid taking
385 actions which might require cleanup before attempting to parse their
386 keyword arguments, since keyword argument parsing functions invoke the
387 @|kw_unknown| handler (\xref{sec:runtime.keywords.unknown}) if they
388 encounter an unknown keyword, and the calling function will not get a
389 chance to tidy up after itself if this happens.
390\end{describe}
391
392As mentioned above, it is not permitted to define an empty keyword set.
393(Specifically, invoking \descref{KWSET_STRUCT}{mac} for an empty keyword set
394would result in attempting to define a structure with no members, which C
395doesn't allow.) On the other hand, keyword arguments are a useful extension
396mechanism, and it's useful to be able to define a function which doesn't
397currently accept any keywords, but which might in the future be extended to
398allow keyword arguments.
399
400\begin{describe}[KW_PARSE_EMPTY]{mac}{KW_PARSE_EMPTY(@<set>, @<kwfirst>);}
401 This is an analogue to \descref{KW_PARSE}{mac} which checks the keyword
402 argument list for a function which accepts no keyword arguments.
403
404 It calls the \descref{kw_parseempty}[function]{fun} with five arguments:
405 the @<set> name, as a string; the string pointer @<kwfirst>; the address of
406 a temporary argument-tail cursor object of type @|va_list|, constructed on
407 the assumption that @<kwfirst> is the enclosing function's final keyword
408 argument; a null pointer; and the value zero (signifying an empty
409 keyword-argument vector).
410
411 The effect is to check that the argument tail contains no keyword arguments
412 other than the special predefined ones.
413\end{describe}
414
415\begin{describe}[KWPARSE_EMPTY]{mac}{KWPARSE_EMPTY(@<set>);}
416 This is an analogue to \descref{KWPARSE}{mac} which checks that the
417 enclosing function has been passed no keyword arguments other than the
418 special predefined ones. It assumes that the first keyword name is in an
419 argument named @|kwfirst_|, as set up by the \descref{KWTAIL}[marker]{mac}.
420\end{describe}
421
422\begin{describe}[kw_parseempty]{fun}
423 {void kw_parseempty(\=const char *@<set>,
424 const char *@<kwfirst>, va_list *@<ap>, \+ \\
425 const struct kwval *@<v>, size_t @<n>);}
426 This function checks an keyword argument list to make sure that contains no
427 keyword arguments (other than the special ones described in
428 \xref{sec:runtime.keywords.calling}).
429
430 The @<set> argument should point to a null-terminated string: this will be
431 reported as the keyword set name to \descref{kw_unknown}{fun}, though it
432 need not (and likely will not) refer to any defined keyword set. The
433 remaining arguments are as for the keyword parsing functions defined by the
434 \descref{KWSET_PARSEFN}[macro]{mac}.
435\end{describe}
436
437\subsection{Function wrappers} \label{sec:runtime.keywords.wrappers}
438
439Most users will not need the hairy machinery involving argument vectors.
440Their main use is in defining \emph{wrapper functions}. Suppose there is a
441function @<f> which accepts some keyword arguments, and we want to write a
442function @<g> which accepts the same keywords recognized by @<f> and some
443additional ones. Unfortunately @<f> may behave differently depending on
444whether or not a particular keyword argument is supplied at all, but it's not
445possible to synthesize a valid @|va_list| other than by simply capturing a
446live argument tail, and it's not possible to decide at runtime whether or not
447to include some arguments in a function call. It's still possible to write
448@<g>, by building a vector of keyword arguments, collected one-by-one
449depending on the corresponding @`_suppliedp' flags.
450
451A few macros are provided to make this task easier.
452
453\begin{describe}[KW_COUNT]{mac}{KW_COUNT(@<set>)}
454 Returns the number of keywords defined in a keyword set named @<set>.
455\end{describe}
456
457\begin{describe}[KW_COPY]{mac}
458 {KW_COPY(@<fromset>, @<toset>, @<kw>, @<v>, @<n>);}
459
460 The macro @|KW_COPY| populates a vector of @|kwval| structures from a
461 keyword-argument structure.
462
463 The @<fromset> and @<toset> arguments should be the names of keyword sets;
464 @<kw> should be an lvalue of type @|@<fromset>{}_kwargs|; @<v> should be
465 the base address of a sufficiently large vector of @|struct kwval| objects;
466 and @<n> should be an lvalue of some appropriate integer type. The
467 @<toset> must be a subset of @<fromset>: i.e., for every keyword defined in
468 @<toset> there is a keyword defined in @<fromset> with the same name and
469 type.
470
471 Successive elements of @<v>, starting at index @<n>, are filled in to refer
472 to the keyword arguments defined in @<toset> whose @`_suppliedp' flag is
473 set in the argument structure pointed to by @<kw>; for each such argument,
474 a pointer to the keyword name is stored in the corresponding vector
475 element's @|kw| member, and a pointer to the argument value, held in the
476 keyword argument structure, is stored in the vector element's @|val|
477 member.
478
479 At the end of this, the index @<n> is advanced so as to contain the index
480 of the first unused element of @<v>. Hence, at most @|KW_COUNT(@<toset>)|
481 elements of @<v> will be used.
482\end{describe}
483
484
485\subsection{Handling unknown-keyword errors}
486\label{sec:runtime.keywords.unknown}
487
488When parsing a variable-length argument tail, it is not possible to continue
489after encountering an unknown keyword name. This is because it is necessary
490to know the (promoted) type of the following argument value in order to skip
491past it; but the only clue provided as to the type is the keyword name, which
492in this case is meaningless.
493
494In this situation, the parser functions generated by
495\descref{KWSET_PARSEFN}{mac} (and the \descref{kw_parseempty}[function]{fun})
496call @|kw_unknown|.
497
498\begin{describe}[kw_unknown]{fun}
499 {void kw_unknown(const char *@<set>, const char *@<kw>);}
500
501 This is a function of two arguments: @<set> points to the name of the
502 keyword set expected by the caller, as a null-terminated string; and @<kw>
503 is the unknown keyword which was encountered. All that @|kw_unknown| does
504 is invoke the function whose address is stored in the global variable
505 \descref{kw_unkhook}{var} with the same arguments.
506
507 This function never returns to its caller: if the @|kw_unkhook| function
508 returns (which it shouldn't) then @|kw_unknown| writes a fatal error
509 message to the standard error stream and calls \man{abort}{3}.
510\end{describe}
511
512\begin{describe}[kw_unkhookfn]{type}
513 {typedef void kw_unkhookfn(const char *@<set>, const char *@<kw>);}
514
515 The @|kw_unkhookfn| type is the type of unknown-keyword handler functions.
516 A handler function is given two arguments, both of which are pointers to
517 null-terminated strings: @<set> is the name of the keyword set expected;
518 and @<kw> is the name of the offending unknown keyword.
519\end{describe}
520
521\begin{describe}[kw_unkhook]{var}{kw_unkhookfn *kw_unkhook}
522 This variable\footnote{%
523 Having a single global hook variable is obviously inadequate for a modern
524 library, but dealing with multiple threads isn't currently possible
525 without writing (moderately complex) system-specific code which would be
526 out of place in this library. The author's intention is that the hook
527 variable @|kw_unkhook| be `owned' by some external library which can make
528 its functionality available to client programs in a safer and more
529 convenient way. On Unix-like platforms (including Cygwin) that library
530 will be (a later version of) \textbf{mLib}; other platforms will likely
531 need different arrangements. The author is willing to coordinate any
532 such efforts.} %
533 holds the current unknown-keyword handler function. It will be invoked by
534 \descref{kw_unknown}{fun}. The function may take whatever action seems
535 appropriate, but should not return to its caller.
536
537 Initially, this variable points to the
538 \descref{kw_defunknown}[function]{fun}.
539\end{describe}
540
541\begin{describe}[kw_defunknown]{fun}
542 {void kw_defunknown(const char *@<set>, const char *@<kw>);}
543 This function simply writes a message to standard error, to the effect that
544 the keyword named by @<kw> is not known in the keyword set @<set>, and
545 calls \man{abort}{3}.
546
547 This function is the default value of the \descref{kw_unkhook}[hook
548 variable]{var}.
549\end{describe}
550
551As an example of the kind of special effect which can be achieved using this
552hook, the following hacking answers whether a function recognizes a
553particular keyword argument.
554
555\begin{prog}
556 \#define KWARGS_TEST(k, val) KWARGS(K(k, val) K(kw.unknown, 0))
557 \\+
558 static jmp_buf kw_test_jmp;
559 \\+
560 static void kw_test_unknown(const char *set, const char *kw) \\
561 \{ \\ \ind
562 if (strcmp(kw, "kw.unknown")) longjmp(kw_test_jmp, 1); \\
563 else longjmp(kw_test_jmp, 2); \- \\
564 \}
565 \\+
566 \#define KW_TEST(flag, set, call) do \{ @\\ \\ \ind
567 kw_unkhookfn *oldunk = kw_unkhook; @\\ \\
568 kw_unkhook = kw_test_unknown; @\\ \\
569 switch (setjmp(kw_test_jmp)) \{ @\\ \\ \ind
570 case 0: call; abort(); @\\ \\
571 case 1: flag = 1; break; @\\ \\
572 case 2: flag = 0; break; @\\ \\
573 default: abort(); \- @\\ \\
574 \} @\\ \\
575 kw_unkhook = oldunk; \- @\\ \\
576 \} while (0)
577 \\+
578 /* Example of use */ \\
579 int f; \\
580 KW_TEST(f, somefunc(1, "two", 3, KWARGS_TEST("shiny", 68.7))); \\
581 /\=* now f is nonzero if `somefunc' accepts the `shiny' keyword \+ \\
582 {}* (which we hope wants a double argument) \\
583 {}*/
584\end{prog}
585
586%%%--------------------------------------------------------------------------
e520bc24
MW
587\section{Object system support} \label{sec:runtime.object}
588
589This section describes the macros and functions exposed in the @|<sod/sod.h>|
590header file which provide assistance for working with Sod classes and
591objects.
62f9852b
MW
592
593The runtime support functionality defined here generally expects that
594instances and classes inherit from the standard @|SodObject| root object.
595While the translator can (at some effort) support alternative roots, they
596will require different run-time support machinery.
597
e520bc24
MW
598
599\subsection{Infrastructure macros} \label{ch:runtime.object.infra}
600
601The runtime support functionality defined here generally expects that
602instances and classes inherit from the standard @|SodObject| root object.
603While the translator can (at some effort) support alternative roots, they
604will require different run-time support machinery.
62f9852b
MW
605
606These macros are mostly intended for use in code generated by the Sod
607translator. Others may find them useful for special effects, but they can be
608tricky to understand and use correctly and can't really be recommended for
609general use.
610
611\begin{describe}[SOD_XCHAIN]{mac}
612 {void *SOD_CHAIN(@<chead>, const @<cls> *@<obj>);}
613 Performs a `cross-chain upcast'.
614
615 Given a pointer @<obj> to an instance of a class of type @<cls> and the
616 nickname @<chead> of the least specific class in one of @<cls>'s superclass
617 chains which does not contain @<cls> itself, @|SOD_XCHAIN| returns the
618 address of that chain's storage within the instance layout as a raw
619 @|void~*| pointer. (Note that @<cls> is not mentioned explicitly.)
620
621 This macro is used by the generated @|@<CLASS>{}__CONV_@<CLS>| conversion
622 macros, which you are encouraged to use instead where possible.
623\end{describe}
624
625\begin{describe}[SOD_OFFSETDIFF]{mac}
09efeb89 626 {ptrdiff_t SOD_OFFSETDIFF(@<type>, @<member>_1, @<member>_2);}
62f9852b
MW
627 Returns the signed offset between two members of a structure or union type.
628
629 Given a structure or union type @<type>, and two member names @<member>_1
630 and @<member>_2, then @|SOD_OFFSETDIFF| gives the difference, in bytes,
631 between the addresses of objects @|$x$.@<member>_1| and @|$x$.@<member>_2|
632 for any object $x$ of type @<type>.
633
634 This macro is used internally when generating vtables and is not expected
635 to be very useful elsewhere.
636\end{describe}
637
638\begin{describe}[SOD_ILAYOUT]{mac}
09efeb89 639 {@<cls>{}__ilayout *SOD_ILAYOUT(@<cls>, @<chead>, const void *@<obj>);}
62f9852b
MW
640 Recovers the instance layout base address from a pointer to one of its
641 instance chains.
642
643 Specifically, given a class name @<cls>, the nickname @<chead> of the least
644 specific class in one of @<cls>'s superclass chains, and a pointer @<obj>
645 to the instance storage for the chain containing @<chead> within a direct
646 instance of @<cls> (i.e., not an instance of any proper subclass),
647 @|SOD_ILAYOUT| returns the a pointer to the layout structure containing
648 @<obj>.
649
650 This macro is used internally in effective method bodies and is not
651 expected to be very useful elsewhere since it's unusual to have such
652 specific knowledge about the dynamic type of an instance. The
653 @|SOD_INSTBASE| macro (described below) is more suited to general use.
654\end{describe}
655
e520bc24
MW
656
657\subsection{Utility macros} \label{sec:runtime.object.utility}
62f9852b
MW
658
659The following macros are expected to be useful in Sod method definitions and
660client code.
661
662\begin{describe}[SOD_CLASSOF]{mac}
09efeb89 663 {const void *SOD_CLASSOF(const @<cls> *@<obj>);}
62f9852b
MW
664 Returns the class object describing an instance's dynamic class.
665
666 Given a pointer @<obj> to an instance, @|SOD_CLASSOF| returns a pointer to
667 @<obj>'s dynamic class, which (assuming @<obj> is typed correctly in the
668 first place) will be a subclass of @<cls>. (If you wanted the class object
669 for @<cls> itself, it's called @|@<cls>{}__class|.)
670\end{describe}
671
672\begin{describe}[SOD_INSTBASE]{mac}{void *SOD_INSTBASE(const @<cls> *@<obj>)}
673 Finds the base address of an instance's layout.
674
675 Given a pointer @<obj> to an instance, @|SOD_INSTBASE| returns the base
676 address of the storage allocated to @<obj>. This is useful if you want to
677 free a dynamically allocated instance, for example.
678
679 This macro needs to look up an offset in @<obj>'s vtable to do its work.
680 Compare @|SOD_ILAYOUT| above, which is faster but requires precise
681 knowledge of the instance's dynamic class.
682\end{describe}
683
684\begin{describe}[SOD_CONVERT]{mac}
09efeb89 685 {@<cls> *SOD_CONVERT(@<cls>, const void *@<obj>);}
62f9852b
MW
686
687 Perform general conversions (up-, down-, and cross-casts) on instance
688 pointers.
689
690 Given a class name @<cls> and a pointer @<obj> to an instance,
691 @|SOD_CONVERT| returns an appropriately converted pointer to @<obj> if
692 @<obj> is indeed an instance of (some subclass of) @<cls>; otherwise it
693 returns a null pointer.
694
695 This macro is a simple wrapper around the @|sod_convert| function described
696 below, which is useful in the common case that the target class is known
697 statically.
698\end{describe}
699
09efeb89 700\begin{describe}[SOD_DECL]{mac}{SOD_DECL(@<cls>, @<var>);}
62f9852b
MW
701 Declares and initializes an instance with automatic storage duration.
702
703 Given a class name @<cls> and an identifier @<var>, @|SOD_DECL| declares
704 @<var> to be a pointer to an instance of @<cls>. The instance is
705 initialized in the sense that its vtable and class pointers have been set
706 up, and slots for which initializers are defined are set to the appropriate
707 initial values.
708
709 The instance has automatic storage duration: pointers to it will become
710 invalid when control exits the scope of the declaration.
711\end{describe}
712
e520bc24
MW
713
714\subsection{Functions} \label{sec:runtime.object.functions}
62f9852b
MW
715
716The following functions are provided in @|libsod|.
717
718\begin{describe}[sod_subclassp]{fun}
0ed1c8a9 719 {int sod_subclassp(const SodClass *@<sub>, const SodClass *@<super>);}
62f9852b
MW
720
721 Decide whether one class @<sub> is actually a subclass of another class
722 @<super>.
723
724 The @<sod_subclassp> function returns nonzero if and only if
725 @<sub> is a subclass of @<super>.
726
727 This involves a run-time trawl through the class structures: while some
728 effort has been made to make it perform well it's still not very fast.
729\end{describe}
730
731\begin{describe}[sod_convert]{fun}
0ed1c8a9 732 {void *sod_convert(const SodClass *@<cls>, const void *@<obj>);}
62f9852b
MW
733 Performs general conversions (up-, down-, and cross-casts) on instance
734 pointers.
735
736 Given a class pointer @<cls> and an instance pointer @<obj>, @|sod_convert|
737 returns an appropriately converted pointer to @<obj> in the case that
738 @<obj> is an instance of (some subclass of) @<cls>; otherwise it returns
739 null.
740
741 This involves a run-time trawl through the class structures: while some
742 effort has been made to make it perform well it's still not very fast. For
743 upcasts (where @<cls> is a superclass of the static type of @<obj>) the
744 automatically defined conversion macros should be used instead, because
745 they're much faster and can't fail. When the target class is known
746 statically, it's slightly more convenient to use the @|SOD_CONVERT| macro
747 instead.
748\end{describe}
749
750%%%----- That's all, folks --------------------------------------------------
751
752%%% Local variables:
753%%% mode: LaTeX
754%%% TeX-master: "sod.tex"
755%%% TeX-PDF-mode: t
756%%% End: