]> git.draconx.ca Git - dxcommon.git/blob - scripts/gen-options.awk
gen-options.awk: Fix generated help text under mawk.
[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.
86 #
87 #   * the object-like macro LOPTS_PACKED_INITIALIZER expands to a
88 #     comma-separated sequence of integer constant expressions, suitable
89 #     for initializing an array of integers.  All values are less than
90 #     2^LOPT_PACK_BITS.
91 #
92 #   * the function-like macro LOPT_UNPACK(opt, x), where opt is an
93 #     lvalue of type 'struct option', and x is one of the array
94 #     elements initialized by LOPTS_PACKED_INITIALIZER.  This expands
95 #     the encoded value and sets the name, has_arg and val members of
96 #     opt appopriately.  The caller should ensure that the flag member
97 #     is set to zero.
98 #
99 # The help text for an individual struct option element may be obtained by
100 # the function
101 #
102 #   struct lopt_help { const char *desc, *arg; }
103 #   *lopt_get_help(const struct option *opt);
104 #
105 # The returned desc and arg pointers point to the argument name and help text
106 # for the argument, respectively, as written in the options specification file.
107 #
108 # License WTFPL2: Do What The Fuck You Want To Public License, version 2.
109 # This is free software: you are free to do what the fuck you want to.
110 # There is NO WARRANTY, to the extent permitted by law.
111
112 END {
113   print "/*"
114   if (FILENAME) {
115     print " * Automatically generated by gen-options.awk from " FILENAME
116   } else {
117     print " * Automatically generated by gen-options.awk"
118   }
119   print " * Do not edit."
120   print " */"
121 }
122
123 BEGIN {
124   has_actions = 0
125   sopt_string = ""
126   num_options = 0
127   lopt = ""
128   err = 0
129 }
130
131 # Parse option specifier lines
132 $0 ~ /^-/ {
133   work = $0
134   arg = lopt = sopt = ""
135   has_arg = 0
136
137   # Extract short option name
138   if (work ~ /^-[^-]/) {
139     sopt = substr(work, 2, 1)
140     sub(/^-.,[ \t]*/, "", work)
141   }
142
143   # Extract long option name
144   if (work ~ /^--/) {
145     if (n = match(work, /[= \t[]/)) {
146       lopt = substr(work, 3, n-3)
147       work = substr(work, n)
148     } else {
149       lopt = substr(work, 3)
150       work = ""
151     }
152   }
153
154   # Extract argument name
155   if (work ~ /^\[=[^\] \t]+\]/) {
156     if (n = index(work, "]")) {
157       arg = substr(work, 3, n-3)
158       work = substr(work, n+1)
159     }
160     has_arg = 2
161   } else if (work ~ /^=/) {
162     if (n = match(work, /[ \t]/)) {
163       arg  = substr(work, 2, n-2)
164       work = substr(work, n)
165     } else {
166       arg  = substr(work, 2)
167       work = ""
168     }
169     has_arg = 1
170   }
171
172   # Extract action
173   sub(/^[ \t]*/, "", work)
174   if (!sopt && work ~ /^\([^, \t]+(,[ \t]*[^, \t]+)?\)/) {
175     # packed form is not possible w/ actions
176     has_actions = 1;
177
178     n = split(work, a, /,[ \t]*/)
179     if (n == 2) {
180       flag = substr(a[1], 2) ", " substr(a[2], 1, length(a[2])-1)
181     } else if (n == 1) {
182       flag = "NULL, " substr(a[1], 2, length(a[1])-2)
183     }
184     sub(/^\([^, \t]+(,[ \t]*[^, \t]+)?/, "", work)
185   } else if (sopt) {
186     flag = "NULL, '" sopt "'"
187   } else {
188     flag = "NULL, " to_enum(lopt)
189   }
190
191   if (work) {
192     print "invalid option specification:", $0 > "/dev/stderr"
193     err = 1
194     exit
195   }
196
197   if (sopt) {
198     sopt_string = sopt_string sopt substr("::", 1, has_arg)
199   }
200   options[num_options++] = lopt
201   optionspec[lopt] = has_arg ", " flag
202   if (arg) {
203     optionarg[lopt] = arg
204   }
205
206   next
207 }
208
209 # Ignore any line beginning with a #
210 $0 ~ /^#/ { next }
211
212 lopt {
213   sub(/^[ \t]*/, "")
214   if (!$0) { next }
215
216   if (lopt in optionhelp)
217     $0 = "\n" $0;
218   optionhelp[lopt] = optionhelp[lopt] $0;
219 }
220
221 # Exit immediately on error
222 END { if (err) { exit err } }
223
224 END {
225   print "#include <stddef.h>"
226   print "#include <limits.h>\n"
227   print "#define SOPT_STRING \"" sopt_string "\"\n"
228 }
229
230 # Generate the main options tables
231 END {
232   lopt_strings = ""
233
234   count = bucketsort(sorted_options, options)
235   for (i = 0; i < count; i++) {
236     lopt_strings = add_to_strtab(lopt_strings, sorted_options[i], offsets)
237   }
238   gsub(/[^ ]+/, "\"&", lopt_strings)
239   gsub(/ /, "\\0\"\n\t", lopt_strings)
240
241   print "static const char lopt_strings[] ="
242   print "\t" lopt_strings "\";\n"
243   print "enum {"
244   for (i = 0; i < count; i++) {
245     opt = options[i]
246     sep = (i+1 == count ? "" : ",")
247
248     print "\t" to_enum(opt), "= UCHAR_MAX+1 +", offsets[opt] sep
249   }
250   print "};"
251   print "#define lopt_str(x) (lopt_strings + (LOPT_ ## x - UCHAR_MAX - 1))"
252
253   if (!has_actions) {
254     output_packed_macros()
255   }
256
257   print "\n#define LOPTS_INITIALIZER \\"
258   for (i = 0; i < count; i++) {
259     opt = options[i]
260     sep = (i+1 == count ? "" : ", \\")
261
262     print "\t/* --" opt, "*/ \\"
263     print "\t{ lopt_strings+" offsets[opt] ",", optionspec[opt] " }" sep
264   }
265 }
266
267 # Generate the help strings
268 END {
269   # First, sort out the argument names
270   arg_strings = ""
271
272   count = bucketsort(sorted_args, optionarg)
273   for (i = 0; i < count; i++) {
274     arg_strings = add_to_strtab(arg_strings, sorted_args[i], arg_offsets)
275   }
276
277   n = split(arg_strings, arg_split)
278   arg_strings = ""
279   for (i = 1; i <= n; i++) {
280     for (opt in optionarg) {
281       if (optionarg[opt] == arg_split[i]) {
282         l10narg[opt] = 1
283         break;
284       }
285     }
286
287     sep = (i < n ? "\"\\0\"" : "")
288     arg_strings = arg_strings "\n\tPN_(\"" opt "\", \"" arg_split[i] "\")" sep
289   }
290
291   print "\n#define ARG_L10N_(x)"
292   print "#ifndef PN_"
293   print "#  define PN_(c, x) x"
294   print "#endif\n"
295
296   print "static const char arg_strings[] = " arg_strings "\"\";"
297   for (opt in optionarg) {
298     if (opt in l10narg) {
299       continue
300     }
301     print "\tARG_L10N_(PN_(\"" opt "\", \"" optionarg[opt] "\"))"
302   }
303
304   # Then add in the actual descriptions
305   print "\nstatic const char help_strings[] ="
306   help = ""
307   help_pos = 0
308   for (opt in options) {
309     opt = options[opt]
310     if (opt in optionhelp) {
311       if (help) {
312         print help "\"\\0\""
313       }
314
315       help = optionhelp[opt]
316       help_offsets[opt] = help_pos
317       help_pos += length(help) + 1
318
319       gsub(/"/, "\\\"", help)
320       gsub(/\n/, "\\n\"\n\t    \"", help)
321       help = "\tPN_(\"" opt "\",\n\t    \"" help "\")"
322     }
323   }
324   print help "\"\";"
325   for (opt in options) {
326     opt = options[opt]
327     if (!(opt in optionhelp)) {
328       print "\tARG_L10N_(PN_(\"" opt "\", \"\"))"
329       help_offsets[opt] = help_pos - 1
330     }
331   }
332
333   print "\nstatic struct lopt_help { const char *desc, *arg; }"
334   print "*lopt_get_help(const struct option *opt, struct lopt_help *out)\n{"
335   print "\tswitch ((opt->name - lopt_strings) + UCHAR_MAX + 1) {"
336   for (opt in options) {
337     opt = options[opt]
338     print "\tcase", to_enum(opt) ":"
339     print "\t\tout->desc = help_strings +", help_offsets[opt] ";"
340     if (opt in optionarg) {
341       print "\t\tout->arg = arg_strings +", arg_offsets[optionarg[opt]] ";"
342     }
343     print "\t\treturn out;"
344   }
345   print "\t}\n\n\treturn NULL;"
346   print "}"
347 }
348
349 # Emit the packed initializer macros.  This is used as an array initializer
350 # that encodes the following information:
351 #
352 #   - short option character offset
353 #   - arg value (0, 1 or 2), and
354 #   - long option string offset
355 #
356 # as a single integer value for each option, in as few bits as practical.
357 #
358 # Currently, this only works if none of the options use action specifications
359 # (as these would require encoding user-specified pointer expressions and
360 # arbitrary int values).
361 function output_packed_macros(i, tmp, accum, max)
362 {
363   print "\n#define LOPT_PACK_BITS (LOPT_SC_BITS + LOPT_HA_BITS + LOPT_LS_BITS)";
364
365   # determine number of bits to encode offsets in SOPT_STRING
366   max = length(sopt_string);
367   accum = 0;
368   for (i = 1; i <= max; i *= 2) {
369     accum++;
370   }
371   print "#define LOPT_SC_BITS " accum;
372
373   # determine number of bits to encode has_arg values
374   max = 0;
375   for (i in optionspec) {
376     tmp = optionspec[i]; sub(/,.*/, "", tmp);
377     if (tmp > max)
378       max = tmp;
379   }
380   print "#define LOPT_HA_BITS " (max > 1 ? 2 : max > 0 ? 1 : 0);
381
382   # determine number of bits to encode offsets in lopt_strings
383   max = 0;
384   for (i in offsets) {
385     if (offsets[i] > max)
386       max = offsets[i];
387   }
388
389   accum = 0;
390   for (i = 1; i <= max; i *= 2) {
391     accum++;
392   }
393   print "#define LOPT_LS_BITS " accum;
394
395   # Now emit the packed initializer macro
396   print "\n#define LOPTS_PACKED_INITIALIZER \\";
397   accum = "";
398   for (i = 0; i < count; i++) {
399     if (accum)
400       print "\t" accum ", \\";
401
402     tmp = options[i];
403     accum = "("offsets[tmp] "ul" "<<LOPT_HA_BITS)";
404     max = tmp = optionspec[tmp];
405     sub(/,.*/, "", max)
406     accum = "((" accum "|" max ")<<LOPT_SC_BITS)";
407
408     sub(/.*[, ]/, "", tmp);
409     if (tmp ~ /^[']/) {
410       tmp = index(sopt_string, substr(tmp, 2, 1)) - 1;
411     } else {
412       tmp = length(sopt_string);
413     }
414     accum = accum "|" tmp;
415   }
416
417   if (accum)
418     print "\t" accum;
419
420   # Finally, the unpack helper macros
421   tmp = "(x) & ((1ul<<LOPT_SC_BITS)-1)";
422   print "\n#define LOPT_UNPACK_VAL(x) \\"
423   print "\t( SOPT_STRING[" tmp "] \\";
424   print "\t? SOPT_STRING[" tmp "] \\";
425   print "\t: 1u + UCHAR_MAX + ((x)>>(LOPT_SC_BITS+LOPT_HA_BITS)))";
426
427   print "\n#define LOPT_UNPACK_ARG(x) \\";
428   print "\t(((x)>>LOPT_SC_BITS)&((1ul<<LOPT_HA_BITS)-1))";
429
430   print "\n#define LOPT_UNPACK_NAME(x) \\"
431   print "\t(lopt_strings+((x)>>(LOPT_SC_BITS+LOPT_HA_BITS)))";
432
433   print "\n#define LOPT_UNPACK(opt, x) do { \\";
434   print "\t(opt).name = LOPT_UNPACK_NAME(x); \\"
435   print "\t(opt).has_arg = LOPT_UNPACK_ARG(x); \\"
436   print "\t(opt).val = LOPT_UNPACK_VAL(x); \\"
437   print "} while (0)";
438 }
439
440 # bucketsort(dst, src)
441 #
442 # Sort the elements of src by descending string length,
443 # placing them into dst[0] ... dst[n].
444 #
445 # Returns the number of elements.
446 function bucketsort(dst, src, buckets, max, count, i, t)
447 {
448   for (t in src) {
449     i = length(src[t])
450     if (i > max) { max = i }
451     buckets[i]++
452   }
453
454   for (i = max; i > 0; i--) {
455     if (i in buckets) {
456       t = buckets[i]
457       buckets[i] = count
458       count += t
459     }
460   }
461
462   for (t in src) {
463     i = length(t = src[t])
464     dst[buckets[i]++] = t
465   }
466
467   return count
468 }
469
470 # to_enum(lopt)
471 #
472 # Return the string LOPT_xxx, where xxx is the argument with all lowercase
473 # letters converted to uppercase, and all non-alphanumeric characters replaced
474 # with underscores.
475 function to_enum(lopt)
476 {
477   lopt = toupper(lopt)
478   gsub(/[^ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]/, "_", lopt)
479   return "LOPT_" lopt
480 }
481
482 # add_to_strtab(strtab, str, offsets)
483 #
484 # Append string to strtab if there is not already a matching string present
485 # in the table.  Newly-added strings are separated by spaces, which must be
486 # translated into null bytes afterwards.  The updated strtab is returned, and
487 # the offsets[str] array member is updated with the position (counting from 0)
488 # of str in the strtab.
489 #
490 # For optimal results, strings should be added in descending length order.
491 function add_to_strtab(strtab, str, offsets, pos)
492 {
493     if ( (pos = index(strtab, str " ") - 1) < 0) {
494       pos = length(strtab)
495       if (pos) {
496         strtab = strtab " " str
497         pos++
498       } else {
499         strtab = strtab str
500       }
501     }
502     offsets[str] = pos
503     return strtab
504 }