]> mj.ucw.cz Git - libucw.git/blob - ucw/opt.c
Opt: compilable, segfaulting.
[libucw.git] / ucw / opt.c
1 /*
2  *      UCW Library -- Parsing of command line options
3  *
4  *      (c) 2013 Jan Moskyto Matejka <mq@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #include <ucw/lib.h>
11 #include <ucw/opt.h>
12 #include <ucw/conf.h>
13 #include <ucw/stkstring.h>
14 #include <ucw/strtonum.h>
15
16 #include <alloca.h>
17
18 static void opt_failure(const char * mesg, ...) FORMAT_CHECK(printf,1,2);
19 static void opt_failure(const char * mesg, ...) {
20   va_list args;
21   va_start(args, mesg);
22   stk_vprintf(mesg, args);
23   exit(OPT_EXIT_BAD_ARGS);
24   va_end(args);
25 }
26
27 struct opt_section * opt_section_root;
28
29 void opt_help_noexit_internal(struct opt_section * help) {
30   uns first_column = 0;
31
32   for (struct opt_item * item = help->opt; item->cls != OPT_CL_END; item++) {
33     if (item->flags & OPT_NO_HELP) continue;
34     if (item->cls == OPT_CL_HELP && item->u.help2 == NULL) continue;
35     if (item->cls == OPT_CL_SECTION) continue;
36     
37     uns linelen = 0;
38     if (item->cls == OPT_CL_HELP) { // two-column help line
39       if (first_column < strlen(item->help))
40         first_column = strlen(item->help);
41       continue;
42     }
43     
44     if (item->letter) { // will write sth like "-x, --exclusive"
45       linelen = strlen("-x, --") + strlen(item->name);
46     }
47     else { // will write sth like "--exclusive"
48       linelen = strlen("--") + strlen(item->name);
49     }
50
51     ASSERT(item->flags & OPT_VALUE_FLAGS);
52
53     if (item->flags & OPT_REQUIRED_VALUE) {
54       linelen += strlen("=value");
55     }
56     else if (item->flags & OPT_MAYBE_VALUE) {
57       linelen += strlen("(=value)");
58     }
59
60     if (linelen > first_column)
61       first_column = linelen;
62   }
63
64   char * spaces = alloca(first_column + 1);
65   char * buf = alloca(first_column + 1);
66   for (uns i=0;i<first_column;i++)
67     spaces[i] = ' ';
68
69   spaces[first_column] = 0;
70
71 #define VAL(it) ((it->flags & OPT_REQUIRED_VALUE) ? "=value" : ((it->flags & OPT_NO_VALUE) ? "" : "(=value)"))
72   for (struct opt_item * item = help->opt; item->cls != OPT_CL_END; item++) {
73     if (item->flags & OPT_NO_HELP) continue;
74     
75     if (item->cls == OPT_CL_HELP) {
76       fprintf(stderr, "%s", item->help);
77       if (item->u.help2 == NULL)
78         fprintf(stderr, "\n");
79       else
80         fprintf(stderr, "%s %s\n", spaces + strlen(item->help), item->u.help2);
81     }
82     else if (item->cls == OPT_CL_SECTION) {
83       opt_help_noexit_internal(item->u.section);
84     }
85     else if (item->letter) {
86       sprintf(buf, "-%c, --%s%s", item->letter, item->name, VAL(item));
87       fprintf(stderr, "%s%s %s\n", buf, spaces + strlen(buf), item->help);
88     }
89     else {
90       sprintf(buf, "--%s%s", item->name, VAL(item));
91       fprintf(stderr, "%s%s %s\n", buf, spaces + strlen(buf), item->help);
92     }
93   }
94 }
95
96 struct opt_precomputed {
97   struct opt_precomputed_option {
98     struct opt_item * item;
99     short flags;
100     short count;
101   } ** opts;
102   struct opt_precomputed_option * shortopt[256];
103   short opt_count;
104 };
105
106 static struct opt_item * opt_find_item_shortopt(int chr, struct opt_precomputed * opts) {
107   return (opts->shortopt[chr] ? opts->shortopt[chr]->item : NULL);
108 }
109
110 static struct opt_item * opt_find_item_longopt(char * str, struct opt_precomputed * pre) {
111   uns len = strlen(str);
112   struct opt_item * candidate = NULL;
113
114   for (int i=0; i<pre->opt_count; i++) {
115     if (!strncmp(pre->opts[i]->item->name, str, len)) {
116       if (strlen(pre->opts[i]->item->name) == len) {
117         if (pre->opts[i]->count++ && (pre->opts[i]->flags & OPT_SINGLE))
118           opt_failure("Option %s appeared the second time.\n", pre->opts[i]->item->name);
119
120         return pre->opts[i]->item;
121       }
122       if (candidate)
123         opt_failure("Ambiguous prefix %s: Found matching %s and %s.\n", str, candidate->name, pre->opts[i]->item->name);
124       else
125         candidate = pre->opts[i]->item;
126     }
127   }
128
129   if (candidate)
130     return candidate;
131
132   opt_failure("Invalid option %s.\n", str);
133 }
134
135 #define OPT_NAME (longopt ? stk_printf("--%s", item->name) : stk_printf("-%c", item->letter))
136 static void opt_parse_value(struct opt_item * item, char * value, int longopt) {
137   switch (item->cls) {
138     case OPT_CL_BOOL:
139       if (!strcasecmp(value, "y") || !strcasecmp(value, "yes") || !strcasecmp(value, "true") || !strcasecmp(value, "1"))
140         *((int *) item->ptr) = 1;
141       else if (!strcasecmp(value, "n") || !strcasecmp(value, "no") || !strcasecmp(value, "false") || !strcasecmp(value, "0"))
142         *((int *) item->ptr) = 0;
143       else
144         opt_failure("Boolean argument for %s has a strange value. Supported (case insensitive): y/n, yes/no, true/false.\n", OPT_NAME);
145       break;
146     case OPT_CL_STATIC:
147       {
148         char * e = NULL;
149         switch (item->type) {
150           case CT_INT:
151             e = cf_parse_int(value, item->ptr);
152             if (e)
153               opt_failure("Integer value parsing failed for argument %s: %s\n", OPT_NAME, e);
154             break;
155           case CT_U64:
156             e = cf_parse_u64(value, item->ptr);
157             if (e)
158               opt_failure("Unsigned 64-bit value parsing failed for argument %s: %s\n", OPT_NAME, e);
159             break;
160           case CT_DOUBLE:
161             e = cf_parse_double(value, item->ptr);
162             if (e)
163               opt_failure("Double value parsing failed for argument %s: %s\n", OPT_NAME, e);
164             break;
165           case CT_IP:
166             e = cf_parse_ip(value, item->ptr);
167             if (e)
168               opt_failure("IP parsing failed for argument %s: %s\n", OPT_NAME, e);
169             break;
170           case CT_STRING:
171             item->ptr = strdup(value);
172             break;
173           default:
174             ASSERT(0);
175         }
176         break;
177       }
178     case OPT_CL_SWITCH:
179       if (*((int *)item->ptr) != -1)
180         opt_failure("Multiple switches: %s", OPT_NAME);
181       else
182         *((int *)item->ptr) = item->u.value;
183       break;
184     case OPT_CL_INC:
185       if (item->flags & OPT_DECREMENT)
186         (*((int *)item->ptr))--;
187       else
188         (*((int *)item->ptr))++;
189     case OPT_CL_CALL:
190       item->u.call(item, value, item->ptr);
191       break;
192     case OPT_CL_USER:
193       {
194         char * e = NULL;
195         e = item->u.utype->parser(value, item->ptr);
196         if (e)
197           opt_failure("User defined type value parsing failed for argument %s: %s\n", OPT_NAME, e);
198         break;
199       }
200     default:
201       ASSERT(0);
202   }
203 }
204 #undef OPT_NAME
205
206 static int opt_longopt(char ** argv, int index, struct opt_precomputed * pre) {
207   int eaten = 0;
208   char * name_in = argv[index] + 2; // skipping the -- on the beginning
209   uns pos = strchrnul(name_in, '=') - name_in;
210   struct opt_item * item = opt_find_item_longopt(strndupa(name_in, pos), pre);
211   char * value = NULL;
212   if (item->flags & OPT_REQUIRED_VALUE) {
213     if (pos < strlen(name_in))
214       value = name_in + pos + 1;
215     else {
216       value = argv[index+1];
217       eaten++;
218     }
219   }
220   else if (item->flags & OPT_MAYBE_VALUE) {
221     if (pos < strlen(name_in))
222       value = name_in + pos + 1;
223   }
224   else {
225     if (pos < strlen(name_in))
226       opt_failure("Argument %s must not have any value.", item->name);
227   }
228   opt_parse_value(item, value, 1);
229   return eaten;
230 }
231
232 static int opt_shortopt(char ** argv, int index, struct opt_precomputed * pre) {
233   int chr = 0;
234   struct opt_item * item;
235   while (argv[index][++chr] && (item = opt_find_item_shortopt(argv[index][chr], pre))) {
236     if (item->flags & OPT_NO_VALUE) {
237       opt_parse_value(item, NULL, 0);
238       continue;
239     }
240     if (chr == 1 && (item->flags & OPT_REQUIRED_VALUE)) {
241       if (argv[index][2]) {
242         opt_parse_value(item, argv[index] + 2, 0);
243         return 0;
244       }
245       else {
246         opt_parse_value(item, argv[index+1], 0);
247         return 1;
248       }
249     }
250     else if (chr == 1 && (item->flags & OPT_MAYBE_VALUE)) {
251       if (argv[index][2])
252         opt_parse_value(item, argv[index] + 2, 0);
253       else
254         opt_parse_value(item, NULL, 0);
255     }
256     else if (item->flags & (OPT_REQUIRED_VALUE | OPT_MAYBE_VALUE)) {
257       if (argv[index][chr+1] || (item->flags | OPT_MAYBE_VALUE))
258         opt_failure("Option -%c may or must have a value but found inside a bunch of short opts.", item->letter);
259       else {
260         opt_parse_value(item, argv[index+1], 0);
261         return 1;
262       }
263     }
264   }
265
266   if (argv[index][chr])
267     opt_failure("Unknown option -%c.", item->letter);
268   
269   return 0;
270 }
271
272 #define OPT_TRAVERSE_SECTIONS \
273   do { \
274     while (item->cls == OPT_CL_SECTION) { \
275       if (stk->next) \
276         stk = stk->next; \
277       else { \
278         struct opt_stack * new_stk = alloca(sizeof(*new_stk)); \
279         new_stk->prev = stk; \
280         stk->next = new_stk; \
281         stk = new_stk; \
282       } \
283       stk->this = item; \
284       item = item->u.section->opt; \
285     } \
286     if (item->cls == OPT_CL_END) { \
287       if (!stk) break; \
288       item = stk->this; \
289       stk = stk->prev; \
290       continue; \
291     } \
292   } while (0)
293
294 void opt_parse(const struct opt_section * options, char ** argv, opt_positional * callback) {
295   struct opt_stack {
296     struct opt_item * this;
297     struct opt_stack * prev;
298     struct opt_stack * next;
299   } * stk = alloca(sizeof(*stk));
300   stk->this = NULL;
301   stk->prev = NULL;
302   stk->next = NULL;
303
304   struct opt_precomputed * pre = alloca(sizeof(*pre));
305
306   int count;
307
308   for (struct opt_item * item = options->opt; ; item++) {
309     OPT_TRAVERSE_SECTIONS;
310     if (item->letter || item->name)
311       count++;
312   }
313   
314   pre->opts = xmalloc(sizeof(*pre->opts) * count);
315   pre->opt_count = 0;
316
317   for (struct opt_item * item = options->opt; ; item++) {
318     OPT_TRAVERSE_SECTIONS;
319     if (item->letter || item->name) {
320       struct opt_precomputed_option * opt = xmalloc(sizeof(*opt));
321       opt->item = item;
322       opt->flags = item->flags;
323       opt->count = 0;
324       pre->opts[pre->opt_count++] = opt;
325       if (item->letter)
326         pre->shortopt[(int) item->letter] = opt;
327       if (!(opt->flags & OPT_VALUE_FLAGS) &&
328           (item->cls == OPT_CL_CALL || item->cls == OPT_CL_USER)) {
329         fprintf(stderr, "You MUST specify some of the value flags for the %c/%s item.\n", item->letter, item->name);
330         ASSERT(0);
331       }
332       else
333         opt->flags |= opt_default_value_flags[item->cls];
334     }
335   }
336
337   int force_positional = 0;
338   for (int i=0;argv[i];i++) {
339     if (argv[i][0] != '-' || force_positional) {
340       callback(argv[i]);
341     }
342     else {
343       if (argv[i][1] == '-') {
344         if (argv[i][2] == '\0')
345           force_positional++;
346         else
347           i += opt_longopt(argv, i, pre);
348       }
349       else if (argv[i][1])
350         i += opt_shortopt(argv, i, pre);
351       else
352         callback(argv[i]);
353     }
354   }
355 }
356
357 #ifdef TEST
358 #include <ucw/fastbuf.h>
359
360 static void show_version(struct opt_item * opt UNUSED, const char * value UNUSED, void * data UNUSED) {
361   printf("This is a simple tea boiling console v0.1.\n");
362   exit(EXIT_SUCCESS);
363 }
364
365 struct teapot_temperature {
366   enum {
367     TEMP_CELSIUS = 0,
368     TEMP_FAHRENHEIT,
369     TEMP_KELVIN,
370     TEMP_REAUMUR,
371     TEMP_RANKINE
372   } scale;
373   int value;
374 } temperature;
375
376 static char * temp_scale_str[] = { "C", "F", "K", "Re", "R" };
377
378 static enum TEAPOT_TYPE {
379   TEAPOT_STANDARD = 0,
380   TEAPOT_EXCLUSIVE,
381   TEAPOT_GLASS,
382   TEAPOT_HANDS,
383   TEAPOT_UNDEFINED = -1
384 } set = TEAPOT_UNDEFINED;
385
386 static int english = 0;
387 static char * name = NULL;
388 static int sugar = 0;
389 static int verbose = 1;
390 static int with_gas = 0;
391 static int black_magic = 0;
392 static int pray = 0;
393 static int water_amount = 0;
394
395 static const char * teapot_temperature_parser(char * in, void * ptr) {
396   struct teapot_temperature * temp = ptr;
397   const char * next;
398   const char * err = str_to_int(&temp->value, in, &next, 0);
399   if (err)
400     return err;
401   if (!strcmp("C", next))
402     temp->scale = TEMP_CELSIUS;
403   else if (!strcmp("F", next))
404     temp->scale = TEMP_FAHRENHEIT;
405   else if (!strcmp("K", next))
406     temp->scale = TEMP_KELVIN;
407   else if (!strcmp("R", next))
408     temp->scale = TEMP_RANKINE;
409   else if (!strcmp("Re", next))
410     temp->scale = TEMP_REAUMUR;
411   else {
412     fprintf(stderr, "Unknown scale: %s\n", next);
413     exit(OPT_EXIT_BAD_ARGS);
414   }
415   return next + strlen(next);
416 }
417
418 static void teapot_temperature_dumper(struct fastbuf * fb, void * ptr) {
419   struct teapot_temperature * temp = ptr;
420   bprintf(fb, "%d%s", temp->value, temp_scale_str[temp->scale]);
421 }
422
423 static struct cf_user_type teapot_temperature_t = {
424   .size = sizeof(struct teapot_temperature),
425   .name = "teapot_temperature_t",
426   .parser = (cf_parser1*) teapot_temperature_parser,
427   .dumper = (cf_dumper1*) teapot_temperature_dumper
428 };
429
430 static struct opt_section water_options = {
431   OPT_ITEMS {
432     OPT_INT('w', "water", water_amount, OPT_REQUIRED | OPT_REQUIRED_VALUE, "Amount of water (in mls)"),
433     OPT_BOOL('G', "with-gas", with_gas, OPT_NO_VALUE, "Use water with gas"),
434     OPT_END
435   }
436 };
437
438 static struct opt_section help = {
439   OPT_ITEMS {
440     OPT_HELP("A simple tea boiling console."),
441     OPT_HELP("Usage: teapot [options] name-of-the-tea"),
442     OPT_HELP("Black, green or white tea supported as well as fruit or herbal tea."),
443     OPT_HELP("You may specify more kinds of tea, all of them will be boiled for you, in the given order."),
444     OPT_HELP(""),
445     OPT_HELP("Options:"),
446     OPT_HELP_OPTION,
447     OPT_CALL('V', "version", show_version, NULL, OPT_NO_VALUE, "Show the version"),
448     OPT_HELP(""),
449     OPT_BOOL('e', "english-style", english, 0, "English style (with milk)"),
450     OPT_INT('s', "sugar", sugar, OPT_REQUIRED_VALUE, "Amount of sugar (in teaspoons)"),
451     OPT_SWITCH(0, "standard-set", set, TEAPOT_STANDARD, 0, "Standard teapot"),
452     OPT_SWITCH('x', "exclusive-set", set, TEAPOT_EXCLUSIVE, 0, "Exclusive teapot"),
453     OPT_SWITCH('g', "glass-set", set, TEAPOT_GLASS, 0, "Transparent glass teapot"),
454     OPT_SWITCH('h', "hands", set, TEAPOT_HANDS, 0, "Use user's hands as a teapot (a bit dangerous)"),
455     OPT_USER('t', "temperature", temperature, teapot_temperature_t, OPT_REQUIRED_VALUE,
456                   "Wanted final temperature of the tea to be served\n"
457               "\t\tSupported scales:\tCelsius [60C], Fahrenheit [140F],"
458               "\t\t\tKelvin [350K], Rankine [600R] and Reaumur [50Re]"
459               "\t\tOnly integer values allowed."),
460     OPT_INC('v', "verbose", verbose, 0, "Verbose (the more -v, the more verbose)"),
461     OPT_INC('q', "quiet", verbose, OPT_DECREMENT, "Quiet (the more -q, the more quiet)"),
462     OPT_INT('b', "black-magic", black_magic, 0, "Use black magic to make the tea extraordinary delicious"),
463     OPT_BOOL('p', "pray", pray, 0, "Pray before boiling"),
464     OPT_HELP(""),
465     OPT_HELP("Water options:"),
466     OPT_SECTION(water_options),
467     OPT_END
468   }
469 };
470
471 #define MAX_TEA_COUNT 30
472 static char * tea_list[MAX_TEA_COUNT];
473 static int tea_num = 0;
474 static void add_tea(const char * name) {
475   if (tea_num >= MAX_TEA_COUNT) {
476     fprintf(stderr, "Cannot boil more than %d teas.\n", MAX_TEA_COUNT);
477     exit(OPT_EXIT_BAD_ARGS);
478   }
479   tea_list[tea_num++] = strdup(name);
480 }
481
482 static void boil_tea(const char * name) {
483   printf("Boiling a tea: %s\n", name);
484 }
485
486 int main(int argc, char ** argv)
487 {
488   opt_parse(&help, argv, add_tea);
489
490   for (int i=0; i<tea_num; i++)
491     boil_tea(tea_list[i]);
492
493   printf("Everything OK. Bye.\n");
494 }
495
496 #endif