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 .\"--------------------------------------------------------------------------
28 .so ../common/defs.man \" @@@PRE@@@
30 .\"--------------------------------------------------------------------------
31 .TH keyword 3 "16 December 2015" "Straylight/Edgeware" "Sensible Object Design"
34 keyword \- keyword argument support library
36 .\"--------------------------------------------------------------------------
38 .B #include <sod/keyword.h>
40 .B "struct kwval { const char *kw; const void *val; };"
42 .B "struct kwtab { const struct kwval *v; size_t n; };"
44 .BI "typedef void kw_unkhookfn(const char *" set ", const char *" kw ");"
46 .BI "#define " set "_KWSET(_) \e"
48 .BI "_(" name ", " type ", " default ") \e"
52 .IB declaration-specifiers " KWSET_STRUCT(" set ");"
54 .IB declaration-specifiers " KWSET_PARSEFN(" set ")"
57 .IB type0 " " func "(" type1 " " arg1 ,
62 .BI "KWDECL(" set ", " kw ");"
64 .BI "KW_PARSE(" set ", " kw ", " kwfirst ");"
66 .BI "KW_PARSE_EMPTY(" set ", " kwfirst ");"
68 .BI "KWPARSE(" set ");"
70 .BI "KWPARSE_EMPTY(" set ");"
79 .BI "K(" name ", " value ")"
81 .BI "K_VALIST(" ap ")"
83 .BI "K_TAB(" v ", " n ")"
96 .BI "KW_COUNT(" set ");"
101 .IB fromset ", " toset ","
103 .BI "const struct " fromset "_kwset *" kw ","
105 .BI "struct kwval *" v ", size_t " n ");"
108 .BI "void kw_unknown(const char *" set ", const char *" kw );
110 .BI "void kw_parseempty(\fP" \c
112 .BI "const char *" set ,
113 .BI "const char *" kwfirst ,
116 .BI "const struct kwval *" v ,
120 .B "kw_unkhookfn *kw_unkhook;"
122 .B "kw_unkhookfn kw_defunknown;"
124 .\"--------------------------------------------------------------------------
129 the actual arguments provided to a function
130 are matched up with the formal arguments
131 given in the function definition
132 according to their ordering in a list.
133 Unless the (rather cumbersome) machinery for dealing with
134 variable-length argument tails
137 exactly the correct number of arguments must be supplied,
138 and in the correct order.
142 is matched by its distinctive
144 rather than by its position in a list.
145 Keyword arguments may be
147 causing some default behaviour by the function.
148 A function can detect whether
149 a particular keyword argument was supplied:
150 so the default behaviour need not be the same as
151 that caused by any specific value of the argument.
153 Keyword arguments can be provided in three ways.
155 Directly, as a variable-length argument tail,
156 consisting (for the most part \(en see below) of alternating
157 keyword names, as pointers to null-terminated strings, and
159 terminated by a null pointer.
160 This is somewhat error-prone,
161 and the support library defines some macros
162 which help ensure that keyword argument lists are well formed.
164 Indirectly, through a
166 object capturing a variable-length argument tail
167 passed to some other function.
168 Such indirect argument tails have the same structure as
169 the direct argument tails described above.
172 objects are hard to copy,
173 the keyword-argument support library consistently passes
177 throughout its programming interface.
179 Indirectly, through a vector of
182 each of which contains
183 a keyword name, as a pointer to a null-terminated string, and
186 of a corresponding argument value.
187 (This indirection is necessary so that
188 the items in the vector can be of uniform size.)
189 Argument vectors are rather inconvenient to use,
190 but are the only practical way in which a caller can decide at runtime
191 which arguments to include in a call,
192 which is useful when writing wrapper functions.
194 Perhaps surprisingly,
195 keyword arguments have a relatively small performance impact.
196 On the author's aging laptop,
197 a call to a simple function,
198 passing two out of three keyword arguments,
199 takes about 30 cycles longer than
200 calling a standard function which just takes integer arguments.
202 quite a lot of code is involved in decoding keyword arguments,
203 so code size will naturally suffer.
206 The header file defines two simple structure types.
215 structure describes a keyword argument name/value pair.
218 member points to the name,
219 as a null-terminated string.
222 member always contains the
225 (This somewhat inconvenient arrangement
228 object independent of the actual argument type.)
231 const struct kwval *v;
237 structure describes a list of keyword arguments,
238 represented as a vector of
243 member points to the start of the vector;
246 member contains the number of elements in the vector.
251 unknown-keyword handler functions.
252 See the descriptions of
258 .SS Calling functions with keyword arguments
259 Functions which accept keyword arguments are ordinary C functions
260 with variable-length argument tails.
261 Hence, they can be called using ordinary C (of the right kind)
262 and all will be well.
263 However, argument lists must follow certain rules
264 (which will be described in full below);
265 failure to do this will result in
266 .IR "undefined behaviour" .
267 The header file provides integration with some C compilers
268 in the form of macros which can be used to help the compiler diagnose
269 errors in calls to keyword-accepting functions;
270 but such support is rather limited at the moment.
271 Some additional macros are provided for use in calls to such functions,
272 and it is recommended that, where possible, these are used.
273 In particular, it's all too easy to forget the trailing null terminator
274 which marks the end of a list of keyword arguments.
276 That said, the underlying machinery is presented first,
277 and the convenience macros are described later.
280 following the mandatory arguments,
281 consists of a sequence of zero or more alternating
283 as pointers to null-terminated strings
285 .BR "const char *" ),
286 and their argument values.
287 This sequence is finally terminated by a null pointer
290 in place of a keyword name.
292 Each function may define for itself which keyword names it accepts,
293 and what types the corresponding argument values should have.
294 There are also (currently) three special keyword names.
297 This special keyword is followed by a pointer to
298 a variable-length argument tail cursor object, of type
300 This cursor object will be modified as the function extracts
301 successive arguments from the tail.
302 The argument tail should consist of alternating
303 keyword names and argument values, as described above,
304 including the first keyword name.
305 (This is therefore different from the convention used when calling
306 keyword argument parser functions:
307 see the description of the
309 macro below for more details about these.)
310 The argument tail may itself contain the special keywords.
313 This special keyword is followed by
316 a pointer to the base of a vector of
319 and the number of elements in this vector
322 Each element of the vector describes a single keyword argument:
325 member points to the keyword's name, and
328 member points to the value.
329 The vector may contain special keywords.
334 argument should contain the address of an object of type
336 (and not point directly to the cursor object,
341 but the cursor will be modified as its argument tail is traversed).
346 argument should contain the address of a
348 structure which itself contains the base address and length of
349 the argument vector to be processed.
352 This keyword is never accepted by any function.
353 If it is encountered,
356 function is called to report the situation as an error;
359 It is possible to construct a circular structure
360 of indirect argument lists
361 (in a number of ways).
362 Don't try to pass such a structure to a function:
363 the result will be unbounded recursion
364 or some other bad outcome.
367 .BI "KWARGS(" body ")"
368 wraps up a sequence of keyword arguments.
371 argument consists of a sequence of calls to
372 the keyword-argument macros described below,
373 one after another without any separation.
375 If there are no keyword arguments,
376 use the argument-less macro
379 There are two reasons for this.
381 C89 doesn't permit empty macro arguments for some reason,
384 is necessary when using a C89 compiler.
386 Omitting the null terminator is a common mistake,
389 tries to get the compiler to warn if you miss it.
392 macro introduces an extra real argument
394 because it's not possible to scan a variable-length argument tail
395 if there are no mandatory arguments.
398 with an empty argument list,
399 then the null terminator is passed as
401 and the variable-length tail ends up empty,
402 which might trigger a compiler warning
403 about the missing terminator.
408 a real one to indicate that there are no keyword arguments,
409 and a dummy one to placate the compiler.
411 The following keyword-argument macros can be used
417 .BI "K(" name ", " value ")"
418 Passes a keyword name and its corresponding value,
419 as a pair of arguments.
422 should be a single identifier
423 (not a quoted string).
426 may be any C expression
427 of the appropriate type.
429 .BI "K_VALIST(" ap ")"
430 Passes an indirect variable-length argument tail.
433 should be an lvalue of type
435 which will be passed by reference.
437 .BI "K_TAB(" v ", " n ")"
438 Passes a vector of keyword arguments.
441 should be the base address of the vector, and
443 should be the number of elements in the vector.
445 .SS Defining functions with keyword arguments
448 defines the collection of keyword arguments
449 accepted by a particular function.
450 The same keyword set may be used by several functions.
451 (If your function currently accepts no keyword arguments,
452 but you plan to add some later,
453 do not define a keyword set,
456 macro described below.)
458 Each keyword set has a name,
459 which is a C identifier.
460 It's good to choose meaningful and distinctive names for keyword sets.
461 Keyword set names are meaningful at runtime:
462 they are used as part of the
464 protocol (described below),
465 and may be examined by handler functions,
466 or reported to a user in error messages.
467 For a keyword set which is used only by a single function,
468 it is recommended that the set be given the same name as the function.
470 The keyword arguments for a keyword set named
472 are described by a `list macro' named
474 This macro takes a single argument,
477 It should expand to a sequence of one or more list items of the form
479 .BI "_(" type ", " name ", " default ")"
481 with no separation between them.
485 #define example_KWSET(_) \e
488 _(const char *, y, NULL)
492 should be a distinct C identifier;
493 they will be used to name structure members.
496 should not end with the suffix
498 (for reasons which will soon become apparent).
508 is a valid declaration:
509 so it may consist of declaration specifiers and
510 (possibly qualified) pointer declarator markers,
511 but not array or function markers
512 (since they must be placed after the
514 This is the same requirement made by the standard
520 should be an initializer expression
521 or brace-enclosed list,
522 suitable for use in an aggregate initializer
523 for a variable with automatic storage duration.
524 (In C89, aggregate initializers may contain only constant expressions;
525 this restriction was lifted in C99.)
529 is expected to be used at the end of function parameter type list
530 to indicate that the function accepts keyword arguments;
531 if there are preceding mandatory arguments
534 marker should be separated from them with a comma
536 (It is permitted for a function parameter type list to contain
542 the macro declares a mandatory argument
543 .B const char *kwfirst_
544 (to collect the first keyword name),
545 and a variable-length argument tail.
550 assumes that the enclosing function's argument list ends with a
553 The marker should be included both in the function's definition and
554 in any declarations, e.g., in the corresponding header file.
558 macro acts as a declaration specifier for
559 functions which accept keyword arguments.
560 Its effect is to arrange for the compiler to check,
561 as far as is possible,
562 that calls to the function are well-formed
563 according to the keyword-argument rules.
564 The exact checking performed depends on the compiler's abilities
565 (and how well supported the compiler is):
566 it may check that every other argument is a string;
567 it may check that the list is terminated with a null pointer;
568 it may not do anything at all.
569 Again, this marker should be included in a function's definition and
575 .IR "keyword structure" .
578 is a keyword-set name then
580 .BI "KWSET_STRUCT(" set ");"
585 For each argument defined in the keyword set,
586 this structure contains two members:
591 listed in the keyword set definition;
592 the other is a 1-bit-wide bitfield of type
595 .IB name _suppliedp \fR.
599 declares and initializes a keyword argument structure variable.
602 is a keyword-set name then
604 .I declaration-specifiers
605 .BI "KWDECL(" set ", " kw ");"
607 declares a variable of type
613 .I declaration-specifiers
614 may provide additional storage-class,
616 or other declaration specifiers.
619 flags are initialized to zero;
620 the other members are initialized with the corresponding defaults
621 from the keyword-set definition.
625 defines a keyword argument
626 .IR "parser function" .
629 is a keyword-set name then
631 .I declaration-specifiers
632 .BI "KWSET_PARSEFN(" set ")"
634 (no trailing semicolon!)
640 .BI "struct " set "_kwargs *" kw ","
642 .BI "const char *" kwfirst ", va_list *" ap ","
644 .BI "const struct kwval *" v ", size_t " n ");"
649 be preceded by storage class specifiers such as
651 for example to adjust the linkage of the name.
652 (I don't recommend declaring parser functions
654 parser functions are somewhat large, and
655 modern compilers are pretty good at
656 figuring out whether to inline static functions.)
658 The function's behaviour is as follows.
659 It parses keyword arguments from
660 a variable-length argument tail, and/or
664 When a keyword argument is recognized,
667 the keyword argument structure pointed to by
673 and the argument value is stored (by simple assignment) in the
678 members are initialized to zero,
679 the caller can determine which keyword arguments were supplied.
680 It is not possible to discover whether two or more arguments
681 have the same keyword:
683 the value from the last such argument is left
684 in the keyword argument structure,
685 and any values from earlier arguments are lost.
691 the variable-length argument tail captured in
694 The variable-argument tail is read from the list described by
696 The argument tail is expected to consist of alternating
697 keyword strings (as ordinary null-terminated strings)
698 and the corresponding values,
699 terminated by a null pointer of type
701 in place of a keyword;
702 except that the first keyword
703 (or terminating null pointer, if no arguments are provided)
704 is expected to have been extracted already
708 the first argument retrieved using the
710 cursor object should then be the value
711 corresponding to the keyword named by
713 (This slightly unusual convention makes it possible for a function to
714 collect the first keyword as a separate mandatory argument,
715 which is essential if there are no other mandatory arguments.
716 It also means that the compiler will emit a diagnostic
717 if you attempt to call a function which expects keyword arguments,
718 but don't supply any and
719 forget the null pointer which terminates the (empty) list.)
725 need not be a valid pointer;
726 otherwise, the cursor object
728 will be modified as the function extracts
729 successive arguments from the tail.
731 The keyword vector is read from the vector of
733 structures starting at address
735 and containing the following
742 need not be a valid pointer.
744 The function also handles the special
748 arguments described above.
749 If an unrecognized keyword argument is encountered,
753 see below for details.
757 macro invokes a keyword argument parsing function.
760 is a keyword-set name,
762 names a keyword argument structure variable of type
767 is the name of the enclosing function's last mandatory argument,
772 .BI "KW_PARSE(" set ", " kw ", " kwfirst ");"
777 the address of the keyword argument structure
781 the address of a temporary argument-tail cursor object of type
783 constructed on the assumption that
785 is the enclosing function's final keyword argument;
787 the value zero (signifying an empty keyword-argument vector).
794 has been defined using
796 then the effect is to parse the keyword arguments passed to the function
797 and set the members of
803 (note the lack of underscore)
810 is a keyword-set name then
812 .BI "KWPARSE(" set ");"
814 declares and initializes a keyword argument structure variable
817 and parses the keyword arguments provided to the enclosing function,
818 storing the results in
820 It assumes that the first keyword name
821 is in an argument named
825 marker described above.
827 The macro expands both to a variable declaration and a statement:
828 in C89, declarations must precede statements,
829 so under C89 rules this macro must appear exactly between
830 the declarations at the head of a brace-enclosed block
831 (typically the function body)
832 and the statements at the end.
833 This restriction was lifted in C99,
834 so the macro may appear anywhere in the function body.
835 However, it is recommended that callers avoid taking actions
836 which might require cleanup
837 before attempting to parse their keyword arguments,
838 since keyword argument parsing functions invoke the
840 handler if they encounter an unknown keyword,
841 and the calling function will not get a chance
842 to tidy up after itself if this happens.
845 it is not permitted to define an empty keyword set.
846 (Specifically, invoking
848 for an empty keyword set would result in attempting to define
849 a structure with no members, which C doesn't allow.)
850 On the other hand, keyword arguments are a useful extension mechanism,
851 and it's useful to be able to define a function which doesn't
852 currently accept any keywords,
853 but which might in the future be extended to allow keyword arguments.
863 and handle this case.
864 These macros take a keyword-set name as an argument,
865 but this name is used only in diagnostic messages
866 (e.g., if an unknown keyword name is encountered)
868 (and probably should not)
869 correspond to a defined keyword set.
873 is an identifier then
875 .BI "KW_PARSE_EMPTY(" set ", " kwfirst ");"
885 the address of a temporary argument-tail cursor object of type
887 constructed on the assumption that
889 is the enclosing function's final keyword argument;
891 the value zero (signifying an empty keyword-argument vector).
892 The effect is to check that the argument tail contains
893 no keyword arguments other than the special predefined ones.
897 is an identifier then
899 .BI "KWPARSE_EMPTY(" set ");"
901 (note the lack of underscore)
902 checks that the enclosing function has been passed
903 no keyword arguments other than the special predefined ones.
904 It assumes that the function's parameter type list ends with the
906 marker described above.
910 function checks an keyword argument list
911 to make sure that contains no keyword arguments
912 (other than the special ones described above).
916 argument should point to a null-terminated string:
917 this will be reported as the keyword set name to
920 (and likely will not)
921 refer to any defined keyword set.
922 The remaining arguments are as for
923 the keyword parsing functions
928 .SS "Wrapper functions"
929 Most users will not need the hairy machinery involving argument vectors.
930 Their main use is in defining
931 .IR "wrapper functions" .
932 Suppose there is a function
934 which accepts some keyword arguments,
935 and we want to write a function
937 which accepts the same keywords recognized by
939 and some additional ones.
942 may behave differently depending on whether or not
943 a particular keyword argument is supplied at all, but
944 it's not possible to synthesize a valid
946 other than by simply capturing a live argument tail,
947 and it's not possible to decide at runtime
948 whether or not to include some arguments in a function call.
949 It's still possible to write
951 by building a vector of keyword arguments,
952 collected one-by-one depending on the corresponding
955 A few macros are provided to make this task easier.
959 returns the number of keywords defined in a keyword set.
962 is a keyword-set name, then
964 .BI "KW_COUNT(" set ")"
966 returns the number of keywords defined by
968 as a constant expression of type
973 populates a vector of
975 structures from a keyword-argument structure.
980 are two keyword-set names then
982 .BI "KW_COPY(" fromset ", " toset ", " kw ", " v ", " n ");"
984 will populate the vector
986 taking argument values from
992 i.e., for every keyword defined in
994 there is a keyword defined in
996 with the same name and type.
997 The remaining arguments are as follows:
1000 .BI "struct " fromset "_kwset"
1001 keyword-argument structure which has been filled in,
1002 e.g., by the keyword-argument parsing function
1003 .IB fromset _kwparse \fR;
1005 is a pointer to a sufficiently large vector of
1010 is an lvalue designating an object of integer type.
1011 Successive elements of
1015 are filled in to refer to
1016 the keyword arguments defined in
1020 flag is set in the argument structure pointed to by
1022 for each such argument,
1023 a pointer to the keyword name is stored in
1024 the corresponding vector element's
1027 a pointer to the argument value,
1028 held in the keyword argument structure,
1029 is stored in the vector element's
1035 is advanced so as to contain the index of the first unused element of
1038 .BI KW_COUNT( toset )
1043 .SS Handling unknown-keyword errors
1044 When parsing a variable-length argument tail,
1045 it is not possible to continue after
1046 encountering an unknown keyword name.
1047 This is because it is necessary
1048 to know the (promoted) type of the following argument value
1049 in order to skip past it;
1050 but the only clue provided as to the type is the keyword name,
1051 which in this case is meaningless.
1054 the parser functions generated by
1061 This is a function of two arguments:
1063 points to the name of the keyword set expected by the caller,
1064 as a null-terminated string; and
1066 is the unknown keyword which was encountered.
1069 does is invoke the function whose address is stored in
1072 with the same arguments.
1075 function never returns to its caller:
1078 function returns (which it shouldn't)
1081 writes a fatal error message to standard error
1087 points to the function
1089 which just writes an error message
1090 quoting the keyword set name
1091 and offending keyword
1096 (In freestanding environments,
1097 the behaviour may be somewhat different:
1098 porting the library to such environments involves
1099 choosing appropriate behaviour for the target platform.)
1101 As an example of the kind of special effect
1102 which can be achieved using this hook,
1103 the following hacking answers whether
1104 a function recognizes a particular keyword argument.
1106 #define KWARGS_TEST(k, val) KWARGS(K(k, val) K(kw.unknown, 0))
1108 static jmp_buf kw_test_jmp;
1110 static void kw_test_unknown(const char *set, const char *kw)
1112 if (strcmp(kw, "kw.unknown")) longjmp(kw_test_jmp, 1);
1113 else longjmp(kw_test_jmp, 2);
1116 #define KW_TEST(flag, set, call) do { \e
1117 kw_unkhookfn *oldunk = kw_unkhook; \e
1118 kw_unkhook = kw_test_unknown; \e
1119 switch (setjmp(kw_test_jmp)) { \e
1120 case 0: call; abort(); \e
1121 case 1: flag = 1; break; \e
1122 case 2: flag = 0; break; \e
1123 default: abort(); \e
1125 kw_unkhook = oldunk; \e
1128 /* Example of use */
1130 KW_TEST(f, somefunc(1, "two", 3, KWARGS_TEST("shiny", 68.7)));
1131 /* now f is nonzero if `somefunc' accepts the `shiny' keyword
1132 * (which we hope wants a double argument)
1136 .\"--------------------------------------------------------------------------
1139 The unknown-keyword hook is inadequate for a modern library,
1140 but dealing with multiple threads isn't currently possible
1141 without writing (moderately complex) system-specific code.
1142 The author's intention is that the hook variable
1144 be `owned' by some external library
1145 which can make its functionality available to client programs
1146 in a safer and more convenient way.
1147 On Unix-like platforms
1149 that library will be (a later version) of
1151 other platforms will likely need different arrangements.
1152 The author is willing to coordinate any such efforts.
1154 The whole interface is rather clunky.
1155 Working with keyword-argument vectors is especially unpleasant.
1156 The remarkable thing is not that it's done well,
1157 but that it can be done at all.
1159 .\"--------------------------------------------------------------------------
1166 .\"--------------------------------------------------------------------------
1170 <mdw@distorted.org.uk>
1172 .\"----- That's all, folks --------------------------------------------------