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