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 In C89, macro actual arguments are not permitted to be empty;
406 if there are no keyword arguments to provide,
407 then the argument-less macro
409 should be used instead.
410 If you're using C99 or later,
411 it's fine to just write
415 The following keyword-argument macros can be used
421 .BI "K(" name ", " value ")"
422 Passes a keyword name and its corresponding value,
423 as a pair of arguments.
426 should be a single identifier
427 (not a quoted string).
430 may be any C expression
431 of the appropriate type.
433 .BI "K_VALIST(" ap ")"
434 Passes an indirect variable-length argument tail.
437 should be an lvalue of type
439 which will be passed by reference.
441 .BI "K_TAB(" v ", " n ")"
442 Passes a vector of keyword arguments.
445 should be the base address of the vector, and
447 should be the number of elements in the vector.
449 .SS Defining functions with keyword arguments
452 defines the collection of keyword arguments
453 accepted by a particular function.
454 The same keyword set may be used by several functions.
455 (If your function currently accepts no keyword arguments,
456 but you plan to add some later,
457 do not define a keyword set,
460 macro described below.)
462 Each keyword set has a name,
463 which is a C identifier.
464 It's good to choose meaningful and distinctive names for keyword sets.
465 Keyword set names are meaningful at runtime:
466 they are used as part of the
468 protocol (described below),
469 and may be examined by handler functions,
470 or reported to a user in error messages.
471 For a keyword set which is used only by a single function,
472 it is recommended that the set be given the same name as the function.
474 The keyword arguments for a keyword set named
476 are described by a `list macro' named
478 This macro takes a single argument,
481 It should expand to a sequence of one or more list items of the form
483 .BI "_(" type ", " name ", " default ")"
485 with no separation between them.
491 #define example_KWSET(_) \e
494 _(const char *, y, NULL)
500 should be a distinct C identifier;
501 they will be used to name structure members.
504 should not end with the suffix
506 (for reasons which will soon become apparent).
516 is a valid declaration:
517 so it may consist of declaration specifiers and
518 (possibly qualified) pointer declarator markers,
519 but not array or function markers
520 (since they must be placed after the
522 This is the same requirement made by the standard
528 should be an initializer expression
529 or brace-enclosed list,
530 suitable for use in an aggregate initializer
531 for a variable with automatic storage duration.
532 (In C89, aggregate initializers may contain only constant expressions;
533 this restriction was lifted in C99.)
537 is expected to be used at the end of function parameter type list
538 to indicate that the function accepts keyword arguments;
539 if there are preceding mandatory arguments
542 marker should be separated from them with a comma
544 (It is permitted for a function parameter type list to contain
550 the macro declares a mandatory argument
551 .B const char *kwfirst_
552 (to collect the first keyword name),
553 and a variable-length argument tail.
558 assumes that the enclosing function's argument list ends with a
561 The marker should be included both in the function's definition and
562 in any declarations, e.g., in the corresponding header file.
566 macro acts as a declaration specifier for
567 functions which accept keyword arguments.
568 Its effect is to arrange for the compiler to check,
569 as far as is possible,
570 that calls to the function are well-formed
571 according to the keyword-argument rules.
572 The exact checking performed depends on the compiler's abilities
573 (and how well supported the compiler is):
574 it may check that every other argument is a string;
575 it may check that the list is terminated with a null pointer;
576 it may not do anything at all.
577 Again, this marker should be included in a function's definition and
583 .IR "keyword structure" .
586 is a keyword-set name then
588 .BI "KWSET_STRUCT(" set ");"
593 For each argument defined in the keyword set,
594 this structure contains two members:
599 listed in the keyword set definition;
600 the other is a 1-bit-wide bitfield of type
603 .IB name _suppliedp \fR.
607 declares and initializes a keyword argument structure variable.
610 is a keyword-set name then
612 .I declaration-specifiers
613 .BI "KWDECL(" set ", " kw ");"
615 declares a variable of type
621 .I declaration-specifiers
622 may provide additional storage-class,
624 or other declaration specifiers.
627 flags are initialized to zero;
628 the other members are initialized with the corresponding defaults
629 from the keyword-set definition.
633 defines a keyword argument
634 .IR "parser function" .
637 is a keyword-set name then
639 .I declaration-specifiers
640 .BI "KWSET_PARSEFN(" set ")"
642 (no trailing semicolon!)
648 .BI "struct " set "_kwargs *" kw ","
650 .BI "const char *" kwfirst ", va_list *" ap ","
652 .BI "const struct kwval *" v ", size_t " n ");"
657 be preceded by storage class specifiers such as
659 for example to adjust the linkage of the name.
660 (I don't recommend declaring parser functions
662 parser functions are somewhat large, and
663 modern compilers are pretty good at
664 figuring out whether to inline static functions.)
666 The function's behaviour is as follows.
667 It parses keyword arguments from
668 a variable-length argument tail, and/or
672 When a keyword argument is recognized,
675 the keyword argument structure pointed to by
681 and the argument value is stored (by simple assignment) in the
686 members are initialized to zero,
687 the caller can determine which keyword arguments were supplied.
688 It is not possible to discover whether two or more arguments
689 have the same keyword:
691 the value from the last such argument is left
692 in the keyword argument structure,
693 and any values from earlier arguments are lost.
699 the variable-length argument tail captured in
702 The variable-argument tail is read from the list described by
704 The argument tail is expected to consist of alternating
705 keyword strings (as ordinary null-terminated strings)
706 and the corresponding values,
707 terminated by a null pointer of type
709 in place of a keyword;
710 except that the first keyword
711 (or terminating null pointer, if no arguments are provided)
712 is expected to have been extracted already
716 the first argument retrieved using the
718 cursor object should then be the value
719 corresponding to the keyword named by
721 (This slightly unusual convention makes it possible for a function to
722 collect the first keyword as a separate mandatory argument,
723 which is essential if there are no other mandatory arguments.
724 It also means that the compiler will emit a diagnostic
725 if you attempt to call a function which expects keyword arguments,
726 but don't supply any and
727 forget the null pointer which terminates the (empty) list.)
733 need not be a valid pointer;
734 otherwise, the cursor object
736 will be modified as the function extracts
737 successive arguments from the tail.
739 The keyword vector is read from the vector of
741 structures starting at address
743 and containing the following
750 need not be a valid pointer.
752 The function also handles the special
756 arguments described above.
757 If an unrecognized keyword argument is encountered,
761 see below for details.
765 macro invokes a keyword argument parsing function.
768 is a keyword-set name,
770 names a keyword argument structure variable of type
775 is the name of the enclosing function's last mandatory argument,
780 .BI "KW_PARSE(" set ", " kw ", " kwfirst ");"
785 the address of the keyword argument structure
789 the address of a temporary argument-tail cursor object of type
791 constructed on the assumption that
793 is the enclosing function's final keyword argument;
795 the value zero (signifying an empty keyword-argument vector).
802 has been defined using
804 then the effect is to parse the keyword arguments passed to the function
805 and set the members of
811 (note the lack of underscore)
818 is a keyword-set name then
820 .BI "KWPARSE(" set ");"
822 declares and initializes a keyword argument structure variable
825 and parses the keyword arguments provided to the enclosing function,
826 storing the results in
828 It assumes that the first keyword name
829 is in an argument named
833 marker described above.
835 The macro expands both to a variable declaration and a statement:
836 in C89, declarations must precede statements,
837 so under C89 rules this macro must appear exactly between
838 the declarations at the head of a brace-enclosed block
839 (typically the function body)
840 and the statements at the end.
841 This restriction was lifted in C99,
842 so the macro may appear anywhere in the function body.
843 However, it is recommended that callers avoid taking actions
844 which might require cleanup
845 before attempting to parse their keyword arguments,
846 since keyword argument parsing functions invoke the
848 handler if they encounter an unknown keyword,
849 and the calling function will not get a chance
850 to tidy up after itself if this happens.
853 it is not permitted to define an empty keyword set.
854 (Specifically, invoking
856 for an empty keyword set would result in attempting to define
857 a structure with no members, which C doesn't allow.)
858 On the other hand, keyword arguments are a useful extension mechanism,
859 and it's useful to be able to define a function which doesn't
860 currently accept any keywords,
861 but which might in the future be extended to allow keyword arguments.
871 and handle this case.
872 These macros take a keyword-set name as an argument,
873 but this name is used only in diagnostic messages
874 (e.g., if an unknown keyword name is encountered)
876 (and probably should not)
877 correspond to a defined keyword set.
881 is an identifier then
883 .BI "KW_PARSE_EMPTY(" set ", " kwfirst ");"
893 the address of a temporary argument-tail cursor object of type
895 constructed on the assumption that
897 is the enclosing function's final keyword argument;
899 the value zero (signifying an empty keyword-argument vector).
900 The effect is to check that the argument tail contains
901 no keyword arguments other than the special predefined ones.
905 is an identifier then
907 .BI "KWPARSE_EMPTY(" set ");"
909 (note the lack of underscore)
910 checks that the enclosing function has been passed
911 no keyword arguments other than the special predefined ones.
912 It assumes that the function's parameter type list ends with the
914 marker described above.
918 function checks an keyword argument list
919 to make sure that contains no keyword arguments
920 (other than the special ones described above).
924 argument should point to a null-terminated string:
925 this will be reported as the keyword set name to
928 (and likely will not)
929 refer to any defined keyword set.
930 The remaining arguments are as for
931 the keyword parsing functions
936 .SS "Wrapper functions"
937 Most users will not need the hairy machinery involving argument vectors.
938 Their main use is in defining
939 .IR "wrapper functions" .
940 Suppose there is a function
942 which accepts some keyword arguments,
943 and we want to write a function
945 which accepts the same keywords recognized by
947 and some additional ones.
950 may behave differently depending on whether or not
951 a particular keyword argument is supplied at all, but
952 it's not possible to synthesize a valid
954 other than by simply capturing a live argument tail,
955 and it's not possible to decide at runtime
956 whether or not to include some arguments in a function call.
957 It's still possible to write
959 by building a vector of keyword arguments,
960 collected one-by-one depending on the corresponding
963 A few macros are provided to make this task easier.
967 returns the number of keywords defined in a keyword set.
970 is a keyword-set name, then
972 .BI "KW_COUNT(" set ")"
974 returns the number of keywords defined by
976 as a constant expression of type
981 populates a vector of
983 structures from a keyword-argument structure.
988 are two keyword-set names then
990 .BI "KW_COPY(" fromset ", " toset ", " kw ", " v ", " n ");"
992 will populate the vector
994 taking argument values from
1000 i.e., for every keyword defined in
1002 there is a keyword defined in
1004 with the same name and type.
1005 The remaining arguments are as follows:
1008 .BI "struct " fromset "_kwset"
1009 keyword-argument structure which has been filled in,
1010 e.g., by the keyword-argument parsing function
1011 .IB fromset _kwparse \fR;
1013 is a pointer to a sufficiently large vector of
1018 is an lvalue designating an object of integer type.
1019 Successive elements of
1023 are filled in to refer to
1024 the keyword arguments defined in
1028 flag is set in the argument structure pointed to by
1030 for each such argument,
1031 a pointer to the keyword name is stored in
1032 the corresponding vector element's
1035 a pointer to the argument value,
1036 held in the keyword argument structure,
1037 is stored in the vector element's
1043 is advanced so as to contain the index of the first unused element of
1046 .BI KW_COUNT( toset )
1051 .SS Handling unknown-keyword errors
1052 When parsing a variable-length argument tail,
1053 it is not possible to continue after
1054 encountering an unknown keyword name.
1055 This is because it is necessary
1056 to know the (promoted) type of the following argument value
1057 in order to skip past it;
1058 but the only clue provided as to the type is the keyword name,
1059 which in this case is meaningless.
1062 the parser functions generated by
1069 This is a function of two arguments:
1071 points to the name of the keyword set expected by the caller,
1072 as a null-terminated string; and
1074 is the unknown keyword which was encountered.
1077 does is invoke the function whose address is stored in
1080 with the same arguments.
1083 function never returns to its caller:
1086 function returns (which it shouldn't)
1089 writes a fatal error message to standard error
1095 points to the function
1097 which just writes an error message
1098 quoting the keyword set name
1099 and offending keyword
1104 (In freestanding environments,
1105 the behaviour may be somewhat different:
1106 porting the library to such environments involves
1107 choosing appropriate behaviour for the target platform.)
1109 As an example of the kind of special effect
1110 which can be achieved using this hook,
1111 the following hacking answers whether
1112 a function recognizes a particular keyword argument.
1116 #define KWARGS_TEST(k, val) KWARGS(K(k, val) K(kw.unknown, 0))
1118 static jmp_buf kw_test_jmp;
1120 static void kw_test_unknown(const char *set, const char *kw)
1122 if (strcmp(kw, "kw.unknown")) longjmp(kw_test_jmp, 1);
1123 else longjmp(kw_test_jmp, 2);
1126 #define KW_TEST(flag, set, call) do { \e
1127 kw_unkhookfn *oldunk = kw_unkhook; \e
1128 kw_unkhook = kw_test_unknown; \e
1129 switch (setjmp(kw_test_jmp)) { \e
1130 case 0: call; abort(); \e
1131 case 1: flag = 1; break; \e
1132 case 2: flag = 0; break; \e
1133 default: abort(); \e
1135 kw_unkhook = oldunk; \e
1138 /* Example of use */
1140 KW_TEST(f, somefunc(1, "two", 3, KWARGS_TEST("shiny", 68.7)));
1141 /* now f is nonzero if `somefunc' accepts the `shiny' keyword
1142 * (which we hope wants a double argument)
1147 .\"--------------------------------------------------------------------------
1150 The unknown-keyword hook is inadequate for a modern library,
1151 but dealing with multiple threads isn't currently possible
1152 without writing (moderately complex) system-specific code.
1153 The author's intention is that the hook variable
1155 be `owned' by some external library
1156 which can make its functionality available to client programs
1157 in a safer and more convenient way.
1158 On Unix-like platforms
1160 that library will be (a later version) of
1162 other platforms will likely need different arrangements.
1163 The author is willing to coordinate any such efforts.
1165 The whole interface is rather clunky.
1166 Working with keyword-argument vectors is especially unpleasant.
1167 The remarkable thing is not that it's done well,
1168 but that it can be done at all.
1170 .\"--------------------------------------------------------------------------
1177 .\"--------------------------------------------------------------------------
1181 <mdw@distorted.org.uk>
1183 .\"----- That's all, folks --------------------------------------------------