]> git.draconx.ca Git - dxcommon.git/blob - scripts/gen-options.awk
Add a helper macro to use the new gen-options packed format.
[dxcommon.git] / scripts / gen-options.awk
1 #!/bin/awk -f
2 #
3 # Copyright © 2021, 2023 Nick Bowler
4 #
5 # Generate definitions helpful when using getopt_long from an options
6 # specification file.
7 #
8 # The options specification file is processed line by line.  Any line
9 # beginning with a - character introduces a new option definition.  Each
10 # option definition specifies any or all of a short option name, a long
11 # option name, an argument specification, and an action specification.
12 #
13 # Only the long option name is mandatory.  It is not possible to define
14 # short options without a corresponding long option.
15 #
16 # The optional short option name is first, and consists of a hyphen (which
17 # must be the first character on the line) followed by the one character
18 # short option name, followed by a comma.
19 #
20 # The long option name is next on the line, which consists of two hyphens
21 # followed by the desired option name.  If the short option name was omitted,
22 # then the first hyphen of the long option name must be the first character
23 # on the line.
24 #
25 # The argument specification is next, consisting of an equals sign followed by
26 # the argument name.  The argument name can be any sequence of non-whitespace
27 # characters and only relevant for --help text.
28 #
29 # If the argument specification is surrounded by square brackets, this
30 # indicates an optional argument.  If the argument specification is omitted
31 # completely, this option has no argument.  Otherwise, the option has a
32 # mandatory argument.
33 #
34 # Finally, the optional action specification defines how the "flag" and
35 # "val" members are set in the option structure for this option.  An action
36 # specification may only be provided for options with no short name.
37 #
38 # If the action specification is omitted, then flag will be set to a null
39 # pointer and val is set to the short option character, if any, otherwise the
40 # unique enumeration constant LOPT_xxx for this option (described below).
41 #
42 # The action specification can be of the form (val) or (flag, val), where flag
43 # and val are C expressions suitable for use in an initializer for objects
44 # with static storage duration.  Neither flag nor val may contain commas or
45 # whitespace.  In the first form, the option's flag is set to a null pointer.
46 #
47 # Any amount of whitespace may follow the short option name, the argument
48 # specification, the action specification, or the comma within an action
49 # specification.  Whitespace is not permitted between a long option name
50 # and a flag specification.
51 #
52 # Examples of option specifications:
53 #
54 #   -h, --help
55 #   --do-nothing (0)
56 #   -o, --output=FILE
57 #   --pad[=VAL]
58 #   --parse-only (&parse_only, 1)
59 #
60 # Each option is assigned an enumeration constant of the form LOPT_xxx,
61 # where xxx is the long option name with all letters in uppercase and
62 # all non-alphanumeric characters replaced with underscores.  The value
63 # of the constants is unspecified, except that they will be unique across
64 # all defined options and distinct from the integer value of any short
65 # option character.
66 #
67 # The object-like macro SOPT_STRING expands to a string literal suitable
68 # for use as the optstring argument to getopt et al.
69 #
70 # The object-like macro LOPTS_INITIALIZER expands to a comma-separated
71 # sequence of struct option initializers, suitable for use in a declaration
72 # of an array of struct option elements with static storage duration.  The
73 # all-zero terminating element required by getopt_long must be added by the
74 # user.  For example:
75 #
76 #   static const struct option lopts[] = { LOPTS_INITIALIZER, {0} };
77 #
78 # If none of the options have action specifications, then an alternate
79 # set of macros is also defined, which encode the struct option array
80 # into a more compact format that can be used to generate the full
81 # 'struct option' array at runtime:
82 #
83 #   * the object-like macro LOPT_PACK_BITS expands to an integer constant
84 #     expression, suitable for use in #if directives, that specifies the
85 #     minimum number of bits required by the encoding.  LOPT_PACK_BITS2
86 #     is the same, but rounded up to the next power of two greater than
87 #     or equal to 8.
88 #
89 #   * the object-like macro LOPTS_PACKED_INITIALIZER expands to a
90 #     comma-separated sequence of integer constant expressions, suitable
91 #     for initializing an array of integers.  All values are less than
92 #     2^LOPT_PACK_BITS.
93 #
94 #   * the function-like macro LOPT_UNPACK(opt, x), where opt is an
95 #     lvalue of type 'struct option', and x is one of the array
96 #     elements initialized by LOPTS_PACKED_INITIALIZER.  This expands
97 #     the encoded value and sets the name, has_arg and val members of
98 #     opt appopriately.  The caller should ensure that the flag member
99 #     is set to zero.
100 #
101 # The help text for an individual struct option element may be obtained by
102 # the function
103 #
104 #   struct lopt_help { const char *desc, *arg; }
105 #   *lopt_get_help(const struct option *opt);
106 #
107 # The returned desc and arg pointers point to the argument name and help text
108 # for the argument, respectively, as written in the options specification file.
109 #
110 # License WTFPL2: Do What The Fuck You Want To Public License, version 2.
111 # This is free software: you are free to do what the fuck you want to.
112 # There is NO WARRANTY, to the extent permitted by law.
113
114 END {
115   print "/*"
116   if (FILENAME) {
117     print " * Automatically generated by gen-options.awk from " FILENAME
118   } else {
119     print " * Automatically generated by gen-options.awk"
120   }
121   print " * Do not edit."
122   print " */"
123 }
124
125 BEGIN {
126   has_actions = 0
127   sopt_string = ""
128   num_options = 0
129   lopt = ""
130   err = 0
131 }
132
133 # Parse option specifier lines
134 $0 ~ /^-/ {
135   work = $0
136   arg = lopt = sopt = ""
137   has_arg = 0
138
139   # Extract short option name
140   if (work ~ /^-[^-]/) {
141     sopt = substr(work, 2, 1)
142     sub(/^-.,[ \t]*/, "", work)
143   }
144
145   # Extract long option name
146   if (work ~ /^--/) {
147     if (n = match(work, /[= \t[]/)) {
148       lopt = substr(work, 3, n-3)
149       work = substr(work, n)
150     } else {
151       lopt = substr(work, 3)
152       work = ""
153     }
154   }
155
156   # Extract argument name
157   if (work ~ /^\[=[^ \t]+\]/ && sub(/\]/, "&", work) == 1) {
158     if (n = index(work, "]")) {
159       arg = substr(work, 3, n-3)
160       work = substr(work, n+1)
161     }
162     has_arg = 2
163   } else if (work ~ /^=/) {
164     if (n = match(work, /[ \t]/)) {
165       arg  = substr(work, 2, n-2)
166       work = substr(work, n)
167     } else {
168       arg  = substr(work, 2)
169       work = ""
170     }
171     has_arg = 1
172   }
173
174   # Extract action
175   sub(/^[ \t]*/, "", work)
176   if (!sopt && work ~ /^\([^, \t]+(,[ \t]*[^, \t]+)?\)/) {
177     # packed form is not possible w/ actions
178     has_actions = 1;
179
180     n = split(work, a, /,[ \t]*/)
181     if (n == 2) {
182       flag = substr(a[1], 2) ", " substr(a[2], 1, length(a[2])-1)
183     } else if (n == 1) {
184       flag = "NULL, " substr(a[1], 2, length(a[1])-2)
185     }
186     sub(/^\([^, \t]+(,[ \t]*[^, \t]+)?/, "", work)
187   } else if (sopt) {
188     flag = "NULL, '" sopt "'"
189   } else {
190     flag = "NULL, " to_enum(lopt)
191   }
192
193   if (work) {
194     print "invalid option specification:", $0 > "/dev/stderr"
195     err = 1
196     exit
197   }
198
199   if (sopt) {
200     sopt_string = sopt_string sopt substr("::", 1, has_arg)
201   }
202   options[num_options++] = lopt
203   optionspec[lopt] = has_arg ", " flag
204   if (arg) {
205     optionarg[lopt] = arg
206   }
207
208   next
209 }
210
211 # Ignore any line beginning with a #
212 $0 ~ /^#/ { next }
213
214 lopt {
215   sub(/^[ \t]*/, "")
216   if (!$0) { next }
217
218   if (lopt in optionhelp)
219     $0 = "\n" $0;
220   optionhelp[lopt] = optionhelp[lopt] $0;
221 }
222
223 # Exit immediately on error
224 END { if (err) { exit err } }
225
226 END {
227   print "#include <stddef.h>"
228   print "#include <limits.h>\n"
229   print "#define SOPT_STRING \"" sopt_string "\"\n"
230 }
231
232 # Generate the main options tables
233 END {
234   lopt_strings = ""
235
236   count = bucketsort(sorted_options, options)
237   for (i = 0; i < count; i++) {
238     lopt_strings = add_to_strtab(lopt_strings, sorted_options[i], offsets)
239   }
240   gsub(/[^ ]+/, "\"&", lopt_strings)
241   gsub(/ /, "\\0\"\n\t", lopt_strings)
242
243   print "static const char lopt_strings[] ="
244   print "\t" lopt_strings "\";\n"
245   print "enum {"
246   for (i = 0; i < count; i++) {
247     opt = options[i]
248     sep = (i+1 == count ? "" : ",")
249
250     print "\t" to_enum(opt), "= UCHAR_MAX+1 +", offsets[opt] sep
251   }
252   print "};"
253   print "#define lopt_str(x) (lopt_strings + (LOPT_ ## x - UCHAR_MAX - 1))"
254
255   if (!has_actions) {
256     output_packed_macros()
257   }
258
259   print "\n#define LOPTS_INITIALIZER \\"
260   for (i = 0; i < count; i++) {
261     opt = options[i]
262     sep = (i+1 == count ? "" : ", \\")
263
264     print "\t/* --" opt, "*/ \\"
265     print "\t{ lopt_strings+" offsets[opt] ",", optionspec[opt] " }" sep
266   }
267 }
268
269 # Generate the help strings
270 END {
271   # First, sort out the argument names
272   arg_strings = ""
273
274   count = bucketsort(sorted_args, optionarg)
275   for (i = 0; i < count; i++) {
276     arg_strings = add_to_strtab(arg_strings, sorted_args[i], arg_offsets)
277   }
278
279   n = split(arg_strings, arg_split)
280   arg_strings = ""
281   for (i = 1; i <= n; i++) {
282     for (opt in optionarg) {
283       if (optionarg[opt] == arg_split[i]) {
284         l10narg[opt] = 1
285         break;
286       }
287     }
288
289     sep = (i < n ? "\"\\0\"" : "")
290     arg_strings = arg_strings "\n\tPN_(\"" opt "\", \"" arg_split[i] "\")" sep
291   }
292
293   print "\n#define ARG_L10N_(x)"
294   print "#ifndef PN_"
295   print "#  define PN_(c, x) x"
296   print "#endif\n"
297
298   print "static const char arg_strings[] = " arg_strings "\"\";"
299   for (opt in optionarg) {
300     if (opt in l10narg) {
301       continue
302     }
303     print "\tARG_L10N_(PN_(\"" opt "\", \"" optionarg[opt] "\"))"
304   }
305
306   # Then add in the actual descriptions
307   print "\nstatic const char help_strings[] ="
308   help = ""
309   help_pos = 0
310   for (opt in options) {
311     opt = options[opt]
312     if (opt in optionhelp) {
313       if (help) {
314         print help "\"\\0\""
315       }
316
317       help = optionhelp[opt]
318       help_offsets[opt] = help_pos
319       help_pos += length(help) + 1
320
321       gsub(/"/, "\\\"", help)
322       gsub(/\n/, "\\n\"\n\t    \"", help)
323       help = "\tPN_(\"" opt "\",\n\t    \"" help "\")"
324     }
325   }
326   print help "\"\";"
327   for (opt in options) {
328     opt = options[opt]
329     if (!(opt in optionhelp)) {
330       print "\tARG_L10N_(PN_(\"" opt "\", \"\"))"
331       help_offsets[opt] = help_pos - 1
332     }
333   }
334
335   print "\nstatic struct lopt_help { const char *desc, *arg; }"
336   print "*lopt_get_help(const struct option *opt, struct lopt_help *out)\n{"
337   print "\tswitch ((opt->name - lopt_strings) + UCHAR_MAX + 1) {"
338   for (opt in options) {
339     opt = options[opt]
340     print "\tcase", to_enum(opt) ":"
341     print "\t\tout->desc = help_strings +", help_offsets[opt] ";"
342     if (opt in optionarg) {
343       print "\t\tout->arg = arg_strings +", arg_offsets[optionarg[opt]] ";"
344     }
345     print "\t\treturn out;"
346   }
347   print "\t}\n\n\treturn NULL;"
348   print "}"
349 }
350
351 # Emit the packed initializer macros.  This is used as an array initializer
352 # that encodes the following information:
353 #
354 #   - short option character offset
355 #   - arg value (0, 1 or 2), and
356 #   - long option string offset
357 #
358 # as a single integer value for each option, in as few bits as practical.
359 #
360 # Currently, this only works if none of the options use action specifications
361 # (as these would require encoding user-specified pointer expressions and
362 # arbitrary int values).
363 function output_packed_macros(i, tmp, accum, max, totalbits)
364 {
365   print "";
366
367   # determine number of bits to encode offsets in SOPT_STRING
368   max = length(sopt_string);
369   totalbits = accum = 0;
370   for (i = 1; i <= max; i *= 2) {
371     accum++;
372   }
373   print "#define LOPT_SC_BITS " accum;
374   totalbits += accum;
375
376   # determine number of bits to encode has_arg values
377   max = 0;
378   for (i in optionspec) {
379     tmp = optionspec[i]; sub(/,.*/, "", tmp);
380     if (tmp > max)
381       max = tmp;
382   }
383   accum = (max > 1 ? 2 : max > 0 ? 1 : 0);
384   print "#define LOPT_HA_BITS " accum;
385   totalbits += accum;
386
387   # determine number of bits to encode offsets in lopt_strings
388   max = 0;
389   for (i in offsets) {
390     if (offsets[i] > max)
391       max = offsets[i];
392   }
393
394   accum = 0;
395   for (i = 1; i <= max; i *= 2) {
396     accum++;
397   }
398   print "#define LOPT_LS_BITS " accum;
399   totalbits += accum;
400
401   print "#define LOPT_PACK_BITS " totalbits;
402   for (i = 8; i < totalbits; i *= 2)
403     ;
404   print "#define LOPT_PACK_BITS2 " i;
405
406   # Now emit the packed initializer macro
407   print "\n#define LOPTS_PACKED_INITIALIZER \\";
408   accum = "";
409   for (i = 0; i < count; i++) {
410     if (accum)
411       print "\t" accum ", \\";
412
413     tmp = options[i];
414     accum = "("offsets[tmp] "ul" "<<LOPT_HA_BITS)";
415     max = tmp = optionspec[tmp];
416     sub(/,.*/, "", max)
417     accum = "((" accum "|" max ")<<LOPT_SC_BITS)";
418
419     sub(/.*[, ]/, "", tmp);
420     if (tmp ~ /^[']/) {
421       tmp = index(sopt_string, substr(tmp, 2, 1)) - 1;
422     } else {
423       tmp = length(sopt_string);
424     }
425     accum = accum "|" tmp;
426   }
427
428   if (accum)
429     print "\t" accum;
430
431   # Finally, the unpack helper macros
432   tmp = "(x) & ((1ul<<LOPT_SC_BITS)-1)";
433   print "\n#define LOPT_UNPACK_VAL(x) \\"
434   print "\t( SOPT_STRING[" tmp "] \\";
435   print "\t? SOPT_STRING[" tmp "] \\";
436   print "\t: 1u + UCHAR_MAX + ((x)>>(LOPT_SC_BITS+LOPT_HA_BITS)))";
437
438   print "\n#define LOPT_UNPACK_ARG(x) \\";
439   print "\t(((x)>>LOPT_SC_BITS)&((1ul<<LOPT_HA_BITS)-1))";
440
441   print "\n#define LOPT_UNPACK_NAME(x) \\"
442   print "\t(lopt_strings+((x)>>(LOPT_SC_BITS+LOPT_HA_BITS)))";
443
444   print "\n#define LOPT_UNPACK(opt, x) do { \\";
445   print "\t(opt).name = LOPT_UNPACK_NAME(x); \\"
446   print "\t(opt).has_arg = LOPT_UNPACK_ARG(x); \\"
447   print "\t(opt).val = LOPT_UNPACK_VAL(x); \\"
448   print "} while (0)";
449 }
450
451 # bucketsort(dst, src)
452 #
453 # Sort the elements of src by descending string length,
454 # placing them into dst[0] ... dst[n].
455 #
456 # Returns the number of elements.
457 function bucketsort(dst, src, buckets, max, count, i, t)
458 {
459   for (t in src) {
460     i = length(src[t])
461     if (i > max) { max = i }
462     buckets[i]++
463   }
464
465   for (i = max; i > 0; i--) {
466     if (i in buckets) {
467       t = buckets[i]
468       buckets[i] = count
469       count += t
470     }
471   }
472
473   for (t in src) {
474     i = length(t = src[t])
475     dst[buckets[i]++] = t
476   }
477
478   return count
479 }
480
481 # to_enum(lopt)
482 #
483 # Return the string LOPT_xxx, where xxx is the argument with all lowercase
484 # letters converted to uppercase, and all non-alphanumeric characters replaced
485 # with underscores.
486 function to_enum(lopt)
487 {
488   lopt = toupper(lopt)
489   gsub(/[^ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]/, "_", lopt)
490   return "LOPT_" lopt
491 }
492
493 # add_to_strtab(strtab, str, offsets)
494 #
495 # Append string to strtab if there is not already a matching string present
496 # in the table.  Newly-added strings are separated by spaces, which must be
497 # translated into null bytes afterwards.  The updated strtab is returned, and
498 # the offsets[str] array member is updated with the position (counting from 0)
499 # of str in the strtab.
500 #
501 # For optimal results, strings should be added in descending length order.
502 function add_to_strtab(strtab, str, offsets, pos)
503 {
504     if ( (pos = index(strtab, str " ") - 1) < 0) {
505       pos = length(strtab)
506       if (pos) {
507         strtab = strtab " " str
508         pos++
509       } else {
510         strtab = strtab str
511       }
512     }
513     offsets[str] = pos
514     return strtab
515 }