3 .\" Keyword argument support
5 .\" (c) 2015 Straylight/Edgeware
8 .\"----- Licensing notice ---------------------------------------------------
10 .\" This file is part of the Sensible Object Design, an object system for C.
12 .\" SOD is free software; you can redistribute it and/or modify
13 .\" it under the terms of the GNU Library General Public License as
14 .\" published by the Free Software Foundation; either version 2 of the
15 .\" License, or (at your option) any later version.
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 Library General Public License for more details.
22 .\" You should have received a copy of the GNU Library General Public
23 .\" License along with SOD; if not, write to the Free
24 .\" Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
25 .\" MA 02111-1307, USA.
27 .\" Highlight using terminal escapes, rather than overstriking.
30 .\" String definitions and font selection.
39 .\" .hP TEXT -- start an indented paragraph with TEXT hanging off to the left
42 \h'-\w'\fB\\$1\ \fP'u'\fB\\$1\ \fP\c
52 .\"--------------------------------------------------------------------------
53 .TH keyword 3 "16 December 2015" "Straylight/Edgeware" "Sensible Object Design"
56 keyword \- keyword argument support library
58 .\"--------------------------------------------------------------------------
60 .B #include <sod/keyword.h>
62 .B "struct kwval { const char *kw; const void *val; };"
64 .B "struct kwtab { const struct kwval *v; size_t n; };"
66 .BI "typedef void kw_unkhookfn(const char *" set ", const char *" kw ");"
68 .BI "#define " set "_KWSET(_) \e"
70 .BI "_(" name ", " type ", " default ") \e"
74 .IB declaration-specifiers " KWSET_STRUCT(" set ");"
76 .IB declaration-specifiers " KWSET_PARSEFN(" set ")"
79 .IB type0 " " func "(" type1 " " arg1 ,
84 .BI "KWDECL(" set ", " kw ");"
86 .BI "KW_PARSE(" set ", " kw ", " kwfirst ");"
88 .BI "KW_PARSE_EMPTY(" set ", " kwfirst ");"
90 .BI "KWPARSE(" set ");"
92 .BI "KWPARSE_EMPTY(" set ");"
101 .BI "K(" name ", " value ")"
103 .BI "K_VALIST(" ap ")"
105 .BI "K_TAB(" v ", " n ")"
118 .BI "KW_COUNT(" set ");"
123 .IB fromset ", " toset ","
125 .BI "const struct " fromset "_kwset *" kw ","
127 .BI "struct kwval *" v ", size_t " n ");"
130 .BI "void kw_unknown(const char *" set ", const char *" kw );
132 .BI "void kw_parseempty(\fP" \c
134 .BI "const char *" set ,
135 .BI "const char *" kwfirst ,
138 .BI "const struct kwval *" v ,
142 .B "kw_unkhookfn *kw_unkhook;"
144 .B "kw_unkhookfn kw_defunknown;"
146 .\"--------------------------------------------------------------------------
151 the actual arguments provided to a function
152 are matched up with the formal arguments
153 given in the function definition
154 according to their ordering in a list.
155 Unless the (rather cumbersome) machinery for dealing with
156 variable-length argument tails
159 exactly the correct number of arguments must be supplied,
160 and in the correct order.
164 is matched by its distinctive
166 rather than by its position in a list.
167 Keyword arguments may be
169 causing some default behaviour by the function.
170 A function can detect whether
171 a particular keyword argument was supplied:
172 so the default behaviour need not be the same as
173 that caused by any specific value of the argument.
175 Keyword arguments can be provided in three ways.
177 Directly, as a variable-length argument tail,
178 consisting (for the most part \(en see below) of alternating
179 keyword names, as pointers to null-terminated strings, and
181 terminated by a null pointer.
182 This is somewhat error-prone,
183 and the support library defines some macros
184 which help ensure that keyword argument lists are well formed.
186 Indirectly, through a
188 object capturing a variable-length argument tail
189 passed to some other function.
190 Such indirect argument tails have the same structure as
191 the direct argument tails described above.
194 objects are hard to copy,
195 the keyword-argument support library consistently passes
199 throughout its programming interface.
201 Indirectly, through a vector of
204 each of which contains
205 a keyword name, as a pointer to a null-terminated string, and
208 of a corresponding argument value.
209 (This indirection is necessary so that
210 the items in the vector can be of uniform size.)
211 Argument vectors are rather inconvenient to use,
212 but are the only practical way in which a caller can decide at runtime
213 which arguments to include in a call,
214 which is useful when writing wrapper functions.
216 Perhaps surprisingly,
217 keyword arguments have a relatively small performance impact.
218 On the author's aging laptop,
219 a call to a simple function,
220 passing two out of three keyword arguments,
221 takes about 30 cycles longer than
222 calling a standard function which just takes integer arguments.
224 quite a lot of code is involved in decoding keyword arguments,
225 so code size will naturally suffer.
228 The header file defines two simple structure types.
241 structure describes a keyword argument name/value pair.
244 member points to the name,
245 as a null-terminated string.
248 member always contains the
251 (This somewhat inconvenient arrangement
254 object independent of the actual argument type.)
260 const struct kwval *v;
267 structure describes a list of keyword arguments,
268 represented as a vector of
273 member points to the start of the vector;
276 member contains the number of elements in the vector.
281 unknown-keyword handler functions.
282 See the descriptions of
288 .SS Calling functions with keyword arguments
289 Functions which accept keyword arguments are ordinary C functions
290 with variable-length argument tails.
291 Hence, they can be called using ordinary C (of the right kind)
292 and all will be well.
293 However, argument lists must follow certain rules
294 (which will be described in full below);
295 failure to do this will result in
296 .IR "undefined behaviour" .
297 The header file provides integration with some C compilers
298 in the form of macros which can be used to help the compiler diagnose
299 errors in calls to keyword-accepting functions;
300 but such support is rather limited at the moment.
301 Some additional macros are provided for use in calls to such functions,
302 and it is recommended that, where possible, these are used.
303 In particular, it's all too easy to forget the trailing null terminator
304 which marks the end of a list of keyword arguments.
306 That said, the underlying machinery is presented first,
307 and the convenience macros are described later.
310 following the mandatory arguments,
311 consists of a sequence of zero or more alternating
313 as pointers to null-terminated strings
315 .BR "const char *" ),
316 and their argument values.
317 This sequence is finally terminated by a null pointer
320 in place of a keyword name.
322 Each function may define for itself which keyword names it accepts,
323 and what types the corresponding argument values should have.
324 There are also (currently) three special keyword names.
327 This special keyword is followed by a pointer to
328 a variable-length argument tail cursor object, of type
330 This cursor object will be modified as the function extracts
331 successive arguments from the tail.
332 The argument tail should consist of alternating
333 keyword names and argument values, as described above,
334 including the first keyword name.
335 (This is therefore different from the convention used when calling
336 keyword argument parser functions:
337 see the description of the
339 macro below for more details about these.)
340 The argument tail may itself contain the special keywords.
343 This special keyword is followed by
346 a pointer to the base of a vector of
349 and the number of elements in this vector
352 Each element of the vector describes a single keyword argument:
355 member points to the keyword's name, and
358 member points to the value.
359 The vector may contain special keywords.
364 argument should contain the address of an object of type
366 (and not point directly to the cursor object,
371 but the cursor will be modified as its argument tail is traversed).
376 argument should contain the address of a
378 structure which itself contains the base address and length of
379 the argument vector to be processed.
382 This keyword is never accepted by any function.
383 If it is encountered,
386 function is called to report the situation as an error;
389 It is possible to construct a circular structure
390 of indirect argument lists
391 (in a number of ways).
392 Don't try to pass such a structure to a function:
393 the result will be unbounded recursion
394 or some other bad outcome.
397 .BI "KWARGS(" body ")"
398 wraps up a sequence of keyword arguments.
401 argument consists of a sequence of calls to
402 the keyword-argument macros described below,
403 one after another without any separation.
405 If there are no keyword arguments,
406 use the argument-less macro
409 There are two reasons for this.
411 C89 doesn't permit empty macro arguments for some reason,
414 is necessary when using a C89 compiler.
416 Omitting the null terminator is a common mistake,
419 tries to get the compiler to warn if you miss it.
422 macro introduces an extra real argument
424 because it's not possible to scan a variable-length argument tail
425 if there are no mandatory arguments.
428 with an empty argument list,
429 then the null terminator is passed as
431 and the variable-length tail ends up empty,
432 which might trigger a compiler warning
433 about the missing terminator.
438 a real one to indicate that there are no keyword arguments,
439 and a dummy one to placate the compiler.
441 The following keyword-argument macros can be used
447 .BI "K(" name ", " value ")"
448 Passes a keyword name and its corresponding value,
449 as a pair of arguments.
452 should be a single identifier
453 (not a quoted string).
456 may be any C expression
457 of the appropriate type.
459 .BI "K_VALIST(" ap ")"
460 Passes an indirect variable-length argument tail.
463 should be an lvalue of type
465 which will be passed by reference.
467 .BI "K_TAB(" v ", " n ")"
468 Passes a vector of keyword arguments.
471 should be the base address of the vector, and
473 should be the number of elements in the vector.
475 .SS Defining functions with keyword arguments
478 defines the collection of keyword arguments
479 accepted by a particular function.
480 The same keyword set may be used by several functions.
481 (If your function currently accepts no keyword arguments,
482 but you plan to add some later,
483 do not define a keyword set,
486 macro described below.)
488 Each keyword set has a name,
489 which is a C identifier.
490 It's good to choose meaningful and distinctive names for keyword sets.
491 Keyword set names are meaningful at runtime:
492 they are used as part of the
494 protocol (described below),
495 and may be examined by handler functions,
496 or reported to a user in error messages.
497 For a keyword set which is used only by a single function,
498 it is recommended that the set be given the same name as the function.
500 The keyword arguments for a keyword set named
502 are described by a `list macro' named
504 This macro takes a single argument,
507 It should expand to a sequence of one or more list items of the form
509 .BI "_(" type ", " name ", " default ")"
511 with no separation between them.
517 #define example_KWSET(_) \e
520 _(const char *, y, NULL)
526 should be a distinct C identifier;
527 they will be used to name structure members.
530 should not end with the suffix
532 (for reasons which will soon become apparent).
542 is a valid declaration:
543 so it may consist of declaration specifiers and
544 (possibly qualified) pointer declarator markers,
545 but not array or function markers
546 (since they must be placed after the
548 This is the same requirement made by the standard
554 should be an initializer expression
555 or brace-enclosed list,
556 suitable for use in an aggregate initializer
557 for a variable with automatic storage duration.
558 (In C89, aggregate initializers may contain only constant expressions;
559 this restriction was lifted in C99.)
563 is expected to be used at the end of function parameter type list
564 to indicate that the function accepts keyword arguments;
565 if there are preceding mandatory arguments
568 marker should be separated from them with a comma
570 (It is permitted for a function parameter type list to contain
576 the macro declares a mandatory argument
577 .B const char *kwfirst_
578 (to collect the first keyword name),
579 and a variable-length argument tail.
584 assumes that the enclosing function's argument list ends with a
587 The marker should be included both in the function's definition and
588 in any declarations, e.g., in the corresponding header file.
592 macro acts as a declaration specifier for
593 functions which accept keyword arguments.
594 Its effect is to arrange for the compiler to check,
595 as far as is possible,
596 that calls to the function are well-formed
597 according to the keyword-argument rules.
598 The exact checking performed depends on the compiler's abilities
599 (and how well supported the compiler is):
600 it may check that every other argument is a string;
601 it may check that the list is terminated with a null pointer;
602 it may not do anything at all.
603 Again, this marker should be included in a function's definition and
609 .IR "keyword structure" .
612 is a keyword-set name then
614 .BI "KWSET_STRUCT(" set ");"
619 For each argument defined in the keyword set,
620 this structure contains two members:
625 listed in the keyword set definition;
626 the other is a 1-bit-wide bitfield of type
629 .IB name _suppliedp \fR.
633 declares and initializes a keyword argument structure variable.
636 is a keyword-set name then
638 .I declaration-specifiers
639 .BI "KWDECL(" set ", " kw ");"
641 declares a variable of type
647 .I declaration-specifiers
648 may provide additional storage-class,
650 or other declaration specifiers.
653 flags are initialized to zero;
654 the other members are initialized with the corresponding defaults
655 from the keyword-set definition.
659 defines a keyword argument
660 .IR "parser function" .
663 is a keyword-set name then
665 .I declaration-specifiers
666 .BI "KWSET_PARSEFN(" set ")"
668 (no trailing semicolon!)
674 .BI "struct " set "_kwargs *" kw ","
676 .BI "const char *" kwfirst ", va_list *" ap ","
678 .BI "const struct kwval *" v ", size_t " n ");"
683 be preceded by storage class specifiers such as
685 for example to adjust the linkage of the name.
686 (I don't recommend declaring parser functions
688 parser functions are somewhat large, and
689 modern compilers are pretty good at
690 figuring out whether to inline static functions.)
692 The function's behaviour is as follows.
693 It parses keyword arguments from
694 a variable-length argument tail, and/or
698 When a keyword argument is recognized,
701 the keyword argument structure pointed to by
707 and the argument value is stored (by simple assignment) in the
712 members are initialized to zero,
713 the caller can determine which keyword arguments were supplied.
714 It is not possible to discover whether two or more arguments
715 have the same keyword:
717 the value from the last such argument is left
718 in the keyword argument structure,
719 and any values from earlier arguments are lost.
725 the variable-length argument tail captured in
728 The variable-argument tail is read from the list described by
730 The argument tail is expected to consist of alternating
731 keyword strings (as ordinary null-terminated strings)
732 and the corresponding values,
733 terminated by a null pointer of type
735 in place of a keyword;
736 except that the first keyword
737 (or terminating null pointer, if no arguments are provided)
738 is expected to have been extracted already
742 the first argument retrieved using the
744 cursor object should then be the value
745 corresponding to the keyword named by
747 (This slightly unusual convention makes it possible for a function to
748 collect the first keyword as a separate mandatory argument,
749 which is essential if there are no other mandatory arguments.
750 It also means that the compiler will emit a diagnostic
751 if you attempt to call a function which expects keyword arguments,
752 but don't supply any and
753 forget the null pointer which terminates the (empty) list.)
759 need not be a valid pointer;
760 otherwise, the cursor object
762 will be modified as the function extracts
763 successive arguments from the tail.
765 The keyword vector is read from the vector of
767 structures starting at address
769 and containing the following
776 need not be a valid pointer.
778 The function also handles the special
782 arguments described above.
783 If an unrecognized keyword argument is encountered,
787 see below for details.
791 macro invokes a keyword argument parsing function.
794 is a keyword-set name,
796 names a keyword argument structure variable of type
801 is the name of the enclosing function's last mandatory argument,
806 .BI "KW_PARSE(" set ", " kw ", " kwfirst ");"
811 the address of the keyword argument structure
815 the address of a temporary argument-tail cursor object of type
817 constructed on the assumption that
819 is the enclosing function's final keyword argument;
821 the value zero (signifying an empty keyword-argument vector).
828 has been defined using
830 then the effect is to parse the keyword arguments passed to the function
831 and set the members of
837 (note the lack of underscore)
844 is a keyword-set name then
846 .BI "KWPARSE(" set ");"
848 declares and initializes a keyword argument structure variable
851 and parses the keyword arguments provided to the enclosing function,
852 storing the results in
854 It assumes that the first keyword name
855 is in an argument named
859 marker described above.
861 The macro expands both to a variable declaration and a statement:
862 in C89, declarations must precede statements,
863 so under C89 rules this macro must appear exactly between
864 the declarations at the head of a brace-enclosed block
865 (typically the function body)
866 and the statements at the end.
867 This restriction was lifted in C99,
868 so the macro may appear anywhere in the function body.
869 However, it is recommended that callers avoid taking actions
870 which might require cleanup
871 before attempting to parse their keyword arguments,
872 since keyword argument parsing functions invoke the
874 handler if they encounter an unknown keyword,
875 and the calling function will not get a chance
876 to tidy up after itself if this happens.
879 it is not permitted to define an empty keyword set.
880 (Specifically, invoking
882 for an empty keyword set would result in attempting to define
883 a structure with no members, which C doesn't allow.)
884 On the other hand, keyword arguments are a useful extension mechanism,
885 and it's useful to be able to define a function which doesn't
886 currently accept any keywords,
887 but which might in the future be extended to allow keyword arguments.
897 and handle this case.
898 These macros take a keyword-set name as an argument,
899 but this name is used only in diagnostic messages
900 (e.g., if an unknown keyword name is encountered)
902 (and probably should not)
903 correspond to a defined keyword set.
907 is an identifier then
909 .BI "KW_PARSE_EMPTY(" set ", " kwfirst ");"
919 the address of a temporary argument-tail cursor object of type
921 constructed on the assumption that
923 is the enclosing function's final keyword argument;
925 the value zero (signifying an empty keyword-argument vector).
926 The effect is to check that the argument tail contains
927 no keyword arguments other than the special predefined ones.
931 is an identifier then
933 .BI "KWPARSE_EMPTY(" set ");"
935 (note the lack of underscore)
936 checks that the enclosing function has been passed
937 no keyword arguments other than the special predefined ones.
938 It assumes that the function's parameter type list ends with the
940 marker described above.
944 function checks an keyword argument list
945 to make sure that contains no keyword arguments
946 (other than the special ones described above).
950 argument should point to a null-terminated string:
951 this will be reported as the keyword set name to
954 (and likely will not)
955 refer to any defined keyword set.
956 The remaining arguments are as for
957 the keyword parsing functions
962 .SS "Wrapper functions"
963 Most users will not need the hairy machinery involving argument vectors.
964 Their main use is in defining
965 .IR "wrapper functions" .
966 Suppose there is a function
968 which accepts some keyword arguments,
969 and we want to write a function
971 which accepts the same keywords recognized by
973 and some additional ones.
976 may behave differently depending on whether or not
977 a particular keyword argument is supplied at all, but
978 it's not possible to synthesize a valid
980 other than by simply capturing a live argument tail,
981 and it's not possible to decide at runtime
982 whether or not to include some arguments in a function call.
983 It's still possible to write
985 by building a vector of keyword arguments,
986 collected one-by-one depending on the corresponding
989 A few macros are provided to make this task easier.
993 returns the number of keywords defined in a keyword set.
996 is a keyword-set name, then
998 .BI "KW_COUNT(" set ")"
1000 returns the number of keywords defined by
1002 as a constant expression of type
1003 .BR "unsigned int" .
1007 populates a vector of
1009 structures from a keyword-argument structure.
1014 are two keyword-set names then
1016 .BI "KW_COPY(" fromset ", " toset ", " kw ", " v ", " n ");"
1018 will populate the vector
1020 taking argument values from
1026 i.e., for every keyword defined in
1028 there is a keyword defined in
1030 with the same name and type.
1031 The remaining arguments are as follows:
1034 .BI "struct " fromset "_kwset"
1035 keyword-argument structure which has been filled in,
1036 e.g., by the keyword-argument parsing function
1037 .IB fromset _kwparse \fR;
1039 is a pointer to a sufficiently large vector of
1044 is an lvalue designating an object of integer type.
1045 Successive elements of
1049 are filled in to refer to
1050 the keyword arguments defined in
1054 flag is set in the argument structure pointed to by
1056 for each such argument,
1057 a pointer to the keyword name is stored in
1058 the corresponding vector element's
1061 a pointer to the argument value,
1062 held in the keyword argument structure,
1063 is stored in the vector element's
1069 is advanced so as to contain the index of the first unused element of
1072 .BI KW_COUNT( toset )
1077 .SS Handling unknown-keyword errors
1078 When parsing a variable-length argument tail,
1079 it is not possible to continue after
1080 encountering an unknown keyword name.
1081 This is because it is necessary
1082 to know the (promoted) type of the following argument value
1083 in order to skip past it;
1084 but the only clue provided as to the type is the keyword name,
1085 which in this case is meaningless.
1088 the parser functions generated by
1095 This is a function of two arguments:
1097 points to the name of the keyword set expected by the caller,
1098 as a null-terminated string; and
1100 is the unknown keyword which was encountered.
1103 does is invoke the function whose address is stored in
1106 with the same arguments.
1109 function never returns to its caller:
1112 function returns (which it shouldn't)
1115 writes a fatal error message to standard error
1121 points to the function
1123 which just writes an error message
1124 quoting the keyword set name
1125 and offending keyword
1130 (In freestanding environments,
1131 the behaviour may be somewhat different:
1132 porting the library to such environments involves
1133 choosing appropriate behaviour for the target platform.)
1135 As an example of the kind of special effect
1136 which can be achieved using this hook,
1137 the following hacking answers whether
1138 a function recognizes a particular keyword argument.
1142 #define KWARGS_TEST(k, val) KWARGS(K(k, val) K(kw.unknown, 0))
1144 static jmp_buf kw_test_jmp;
1146 static void kw_test_unknown(const char *set, const char *kw)
1148 if (strcmp(kw, "kw.unknown")) longjmp(kw_test_jmp, 1);
1149 else longjmp(kw_test_jmp, 2);
1152 #define KW_TEST(flag, set, call) do { \e
1153 kw_unkhookfn *oldunk = kw_unkhook; \e
1154 kw_unkhook = kw_test_unknown; \e
1155 switch (setjmp(kw_test_jmp)) { \e
1156 case 0: call; abort(); \e
1157 case 1: flag = 1; break; \e
1158 case 2: flag = 0; break; \e
1159 default: abort(); \e
1161 kw_unkhook = oldunk; \e
1164 /* Example of use */
1166 KW_TEST(f, somefunc(1, "two", 3, KWARGS_TEST("shiny", 68.7)));
1167 /* now f is nonzero if `somefunc' accepts the `shiny' keyword
1168 * (which we hope wants a double argument)
1173 .\"--------------------------------------------------------------------------
1176 The unknown-keyword hook is inadequate for a modern library,
1177 but dealing with multiple threads isn't currently possible
1178 without writing (moderately complex) system-specific code.
1179 The author's intention is that the hook variable
1181 be `owned' by some external library
1182 which can make its functionality available to client programs
1183 in a safer and more convenient way.
1184 On Unix-like platforms
1186 that library will be (a later version) of
1188 other platforms will likely need different arrangements.
1189 The author is willing to coordinate any such efforts.
1191 The whole interface is rather clunky.
1192 Working with keyword-argument vectors is especially unpleasant.
1193 The remarkable thing is not that it's done well,
1194 but that it can be done at all.
1196 .\"--------------------------------------------------------------------------
1203 .\"--------------------------------------------------------------------------
1207 <mdw@distorted.org.uk>
1209 .\"----- That's all, folks --------------------------------------------------