argpar_iter_parse_next(): make the `error` parameter optional
[argpar.git] / argpar / argpar.c
... / ...
CommitLineData
1/*
2 * SPDX-License-Identifier: MIT
3 *
4 * Copyright (c) 2019-2021 Philippe Proulx <pproulx@efficios.com>
5 * Copyright (c) 2020-2021 Simon Marchi <simon.marchi@efficios.com>
6 */
7
8#include <assert.h>
9#include <stdarg.h>
10#include <stdbool.h>
11#include <stdio.h>
12#include <stdlib.h>
13#include <string.h>
14
15#include "argpar.h"
16
17#define ARGPAR_REALLOC(_ptr, _type, _nmemb) \
18 ((_type *) realloc(_ptr, (_nmemb) * sizeof(_type)))
19
20#define ARGPAR_CALLOC(_type, _nmemb) \
21 ((_type *) calloc((_nmemb), sizeof(_type)))
22
23#define ARGPAR_ZALLOC(_type) ARGPAR_CALLOC(_type, 1)
24
25#define ARGPAR_ASSERT(_cond) assert(_cond)
26
27#ifdef __MINGW_PRINTF_FORMAT
28# define ARGPAR_PRINTF_FORMAT __MINGW_PRINTF_FORMAT
29#else
30# define ARGPAR_PRINTF_FORMAT printf
31#endif
32
33/*
34 * An argpar iterator.
35 *
36 * Such a structure contains the state of an iterator between
37 * calls to argpar_iter_parse_next().
38 */
39struct argpar_iter {
40 /*
41 * Data provided by the user to argpar_iter_create(); immutable
42 * afterwards.
43 */
44 unsigned int argc;
45 const char * const *argv;
46 const struct argpar_opt_descr *descrs;
47
48 /*
49 * Index of the argument to process in the next
50 * argpar_iter_parse_next() call.
51 */
52 unsigned int i;
53
54 /* Counter of non-option arguments */
55 int non_opt_index;
56
57 /*
58 * Current character of the current short option group: if it's
59 * not `NULL`, the parser is in within a short option group,
60 * therefore it must resume there in the next
61 * argpar_iter_parse_next() call.
62 */
63 const char *short_opt_ch;
64};
65
66/* Base parsing item */
67struct argpar_item {
68 enum argpar_item_type type;
69};
70
71/* Option parsing item */
72struct argpar_item_opt {
73 struct argpar_item base;
74
75 /* Corresponding descriptor */
76 const struct argpar_opt_descr *descr;
77
78 /* Argument, or `NULL` if none; owned by this */
79 char *arg;
80};
81
82/* Non-option parsing item */
83struct argpar_item_non_opt {
84 struct argpar_item base;
85
86 /*
87 * Complete argument, pointing to one of the entries of the
88 * original arguments (`argv`).
89 */
90 const char *arg;
91
92 /*
93 * Index of this argument amongst all original arguments
94 * (`argv`).
95 */
96 unsigned int orig_index;
97
98 /* Index of this argument amongst other non-option arguments */
99 unsigned int non_opt_index;
100};
101
102static __attribute__((format(ARGPAR_PRINTF_FORMAT, 1, 0)))
103char *argpar_vasprintf(const char * const fmt, va_list args)
104{
105 int len1, len2;
106 char *str;
107 va_list args2;
108
109 va_copy(args2, args);
110 len1 = vsnprintf(NULL, 0, fmt, args);
111 if (len1 < 0) {
112 str = NULL;
113 goto end;
114 }
115
116 str = malloc(len1 + 1);
117 if (!str) {
118 goto end;
119 }
120
121 len2 = vsnprintf(str, len1 + 1, fmt, args2);
122 ARGPAR_ASSERT(len1 == len2);
123
124end:
125 va_end(args2);
126 return str;
127}
128
129
130static __attribute__((format(ARGPAR_PRINTF_FORMAT, 1, 2)))
131char *argpar_asprintf(const char * const fmt, ...)
132{
133 va_list args;
134 char *str;
135
136 va_start(args, fmt);
137 str = argpar_vasprintf(fmt, args);
138 va_end(args);
139 return str;
140}
141
142static __attribute__((format(ARGPAR_PRINTF_FORMAT, 2, 3)))
143bool try_append_string_printf(char ** const str, const char *fmt, ...)
144{
145 char *new_str = NULL;
146 char *addendum = NULL;
147 bool success;
148 va_list args;
149
150 if (!str) {
151 success = true;
152 goto end;
153 }
154
155 ARGPAR_ASSERT(str);
156 va_start(args, fmt);
157 addendum = argpar_vasprintf(fmt, args);
158 va_end(args);
159
160 if (!addendum) {
161 success = false;
162 goto end;
163 }
164
165 new_str = argpar_asprintf("%s%s", *str ? *str : "", addendum);
166 if (!new_str) {
167 success = false;
168 goto end;
169 }
170
171 free(*str);
172 *str = new_str;
173 success = true;
174
175end:
176 free(addendum);
177 return success;
178}
179
180ARGPAR_HIDDEN
181enum argpar_item_type argpar_item_type(const struct argpar_item * const item)
182{
183 ARGPAR_ASSERT(item);
184 return item->type;
185}
186
187ARGPAR_HIDDEN
188const struct argpar_opt_descr *argpar_item_opt_descr(
189 const struct argpar_item * const item)
190{
191 ARGPAR_ASSERT(item);
192 ARGPAR_ASSERT(item->type == ARGPAR_ITEM_TYPE_OPT);
193 return ((const struct argpar_item_opt *) item)->descr;
194}
195
196ARGPAR_HIDDEN
197const char *argpar_item_opt_arg(const struct argpar_item * const item)
198{
199 ARGPAR_ASSERT(item);
200 ARGPAR_ASSERT(item->type == ARGPAR_ITEM_TYPE_OPT);
201 return ((const struct argpar_item_opt *) item)->arg;
202}
203
204ARGPAR_HIDDEN
205const char *argpar_item_non_opt_arg(const struct argpar_item * const item)
206{
207 ARGPAR_ASSERT(item);
208 ARGPAR_ASSERT(item->type == ARGPAR_ITEM_TYPE_NON_OPT);
209 return ((const struct argpar_item_non_opt *) item)->arg;
210}
211
212ARGPAR_HIDDEN
213unsigned int argpar_item_non_opt_orig_index(
214 const struct argpar_item * const item)
215{
216 ARGPAR_ASSERT(item);
217 ARGPAR_ASSERT(item->type == ARGPAR_ITEM_TYPE_NON_OPT);
218 return ((const struct argpar_item_non_opt *) item)->orig_index;
219}
220
221ARGPAR_HIDDEN
222unsigned int argpar_item_non_opt_non_opt_index(
223 const struct argpar_item * const item)
224{
225 ARGPAR_ASSERT(item);
226 ARGPAR_ASSERT(item->type == ARGPAR_ITEM_TYPE_NON_OPT);
227 return ((const struct argpar_item_non_opt *) item)->non_opt_index;
228}
229
230ARGPAR_HIDDEN
231void argpar_item_destroy(const struct argpar_item * const item)
232{
233 if (!item) {
234 goto end;
235 }
236
237 if (item->type == ARGPAR_ITEM_TYPE_OPT) {
238 struct argpar_item_opt * const opt_item =
239 (struct argpar_item_opt *) item;
240
241 free(opt_item->arg);
242 }
243
244 free((void *) item);
245
246end:
247 return;
248}
249
250static
251bool push_item(struct argpar_item_array * const array,
252 const struct argpar_item * const item)
253{
254 bool success;
255
256 ARGPAR_ASSERT(array);
257 ARGPAR_ASSERT(item);
258
259 if (array->n_items == array->n_alloc) {
260 const unsigned int new_n_alloc = array->n_alloc * 2;
261 const struct argpar_item ** const new_items =
262 ARGPAR_REALLOC(array->items, const struct argpar_item *,
263 new_n_alloc);
264 if (!new_items) {
265 success = false;
266 goto end;
267 }
268
269 array->n_alloc = new_n_alloc;
270 array->items = new_items;
271 }
272
273 array->items[array->n_items] = item;
274 array->n_items++;
275 success = true;
276
277end:
278 return success;
279}
280
281static
282void destroy_item_array(struct argpar_item_array * const array)
283{
284 if (array) {
285 unsigned int i;
286
287 for (i = 0; i < array->n_items; i++) {
288 argpar_item_destroy(array->items[i]);
289 }
290
291 free(array->items);
292 free(array);
293 }
294}
295
296static
297struct argpar_item_array *create_item_array(void)
298{
299 struct argpar_item_array *ret;
300 const int initial_size = 10;
301
302 ret = ARGPAR_ZALLOC(struct argpar_item_array);
303 if (!ret) {
304 goto end;
305 }
306
307 ret->items = ARGPAR_CALLOC(const struct argpar_item *, initial_size);
308 if (!ret->items) {
309 goto error;
310 }
311
312 ret->n_alloc = initial_size;
313 goto end;
314
315error:
316 destroy_item_array(ret);
317 ret = NULL;
318
319end:
320 return ret;
321}
322
323static
324struct argpar_item_opt *create_opt_item(
325 const struct argpar_opt_descr * const descr,
326 const char * const arg)
327{
328 struct argpar_item_opt *opt_item =
329 ARGPAR_ZALLOC(struct argpar_item_opt);
330
331 if (!opt_item) {
332 goto end;
333 }
334
335 opt_item->base.type = ARGPAR_ITEM_TYPE_OPT;
336 opt_item->descr = descr;
337
338 if (arg) {
339 opt_item->arg = strdup(arg);
340 if (!opt_item->arg) {
341 goto error;
342 }
343 }
344
345 goto end;
346
347error:
348 argpar_item_destroy(&opt_item->base);
349 opt_item = NULL;
350
351end:
352 return opt_item;
353}
354
355static
356struct argpar_item_non_opt *create_non_opt_item(const char * const arg,
357 const unsigned int orig_index,
358 const unsigned int non_opt_index)
359{
360 struct argpar_item_non_opt * const non_opt_item =
361 ARGPAR_ZALLOC(struct argpar_item_non_opt);
362
363 if (!non_opt_item) {
364 goto end;
365 }
366
367 non_opt_item->base.type = ARGPAR_ITEM_TYPE_NON_OPT;
368 non_opt_item->arg = arg;
369 non_opt_item->orig_index = orig_index;
370 non_opt_item->non_opt_index = non_opt_index;
371
372end:
373 return non_opt_item;
374}
375
376static
377const struct argpar_opt_descr *find_descr(
378 const struct argpar_opt_descr * const descrs,
379 const char short_name, const char * const long_name)
380{
381 const struct argpar_opt_descr *descr;
382
383 for (descr = descrs; descr->short_name || descr->long_name; descr++) {
384 if (short_name && descr->short_name &&
385 short_name == descr->short_name) {
386 goto end;
387 }
388
389 if (long_name && descr->long_name &&
390 strcmp(long_name, descr->long_name) == 0) {
391 goto end;
392 }
393 }
394
395end:
396 return !descr->short_name && !descr->long_name ? NULL : descr;
397}
398
399enum parse_orig_arg_opt_ret {
400 PARSE_ORIG_ARG_OPT_RET_OK,
401 PARSE_ORIG_ARG_OPT_RET_ERROR_UNKNOWN_OPT = -2,
402 PARSE_ORIG_ARG_OPT_RET_ERROR = -1,
403};
404
405static
406enum parse_orig_arg_opt_ret parse_short_opts(const char * const short_opts,
407 const char * const next_orig_arg,
408 const struct argpar_opt_descr * const descrs,
409 struct argpar_iter * const iter,
410 char ** const error, struct argpar_item ** const item)
411{
412 enum parse_orig_arg_opt_ret ret = PARSE_ORIG_ARG_OPT_RET_OK;
413 bool used_next_orig_arg = false;
414 const char *opt_arg = NULL;
415 const struct argpar_opt_descr *descr;
416 struct argpar_item_opt *opt_item;
417
418 if (strlen(short_opts) == 0) {
419 try_append_string_printf(error, "Invalid argument");
420 goto error;
421 }
422
423 if (!iter->short_opt_ch) {
424 iter->short_opt_ch = short_opts;
425 }
426
427 /* Find corresponding option descriptor */
428 descr = find_descr(descrs, *iter->short_opt_ch, NULL);
429 if (!descr) {
430 ret = PARSE_ORIG_ARG_OPT_RET_ERROR_UNKNOWN_OPT;
431 try_append_string_printf(error, "Unknown option `-%c`",
432 *iter->short_opt_ch);
433 goto error;
434 }
435
436 if (descr->with_arg) {
437 if (iter->short_opt_ch[1]) {
438 /* `-oarg` form */
439 opt_arg = &iter->short_opt_ch[1];
440 } else {
441 /* `-o arg` form */
442 opt_arg = next_orig_arg;
443 used_next_orig_arg = true;
444 }
445
446 /*
447 * We accept `-o ''` (empty option argument), but not
448 * `-o` alone if an option argument is expected.
449 */
450 if (!opt_arg || (iter->short_opt_ch[1] &&
451 strlen(opt_arg) == 0)) {
452 try_append_string_printf(error,
453 "Missing required argument for option `-%c`",
454 *iter->short_opt_ch);
455 used_next_orig_arg = false;
456 goto error;
457 }
458 }
459
460 /* Create and append option argument */
461 opt_item = create_opt_item(descr, opt_arg);
462 if (!opt_item) {
463 goto error;
464 }
465
466 *item = &opt_item->base;
467 iter->short_opt_ch++;
468
469 if (descr->with_arg || !*iter->short_opt_ch) {
470 /* Option has an argument: no more options */
471 iter->short_opt_ch = NULL;
472
473 if (used_next_orig_arg) {
474 iter->i += 2;
475 } else {
476 iter->i++;
477 }
478 }
479
480 goto end;
481
482error:
483 if (ret == PARSE_ORIG_ARG_OPT_RET_OK) {
484 ret = PARSE_ORIG_ARG_OPT_RET_ERROR;
485 }
486
487end:
488 return ret;
489}
490
491static
492enum parse_orig_arg_opt_ret parse_long_opt(const char * const long_opt_arg,
493 const char * const next_orig_arg,
494 const struct argpar_opt_descr * const descrs,
495 struct argpar_iter * const iter,
496 char ** const error, struct argpar_item ** const item)
497{
498 const size_t max_len = 127;
499 enum parse_orig_arg_opt_ret ret = PARSE_ORIG_ARG_OPT_RET_OK;
500 const struct argpar_opt_descr *descr;
501 struct argpar_item_opt *opt_item;
502 bool used_next_orig_arg = false;
503
504 /* Option's argument, if any */
505 const char *opt_arg = NULL;
506
507 /* Position of first `=`, if any */
508 const char *eq_pos;
509
510 /* Buffer holding option name when `long_opt_arg` contains `=` */
511 char buf[max_len + 1];
512
513 /* Option name */
514 const char *long_opt_name = long_opt_arg;
515
516 if (strlen(long_opt_arg) == 0) {
517 try_append_string_printf(error, "Invalid argument");
518 goto error;
519 }
520
521 /* Find the first `=` in original argument */
522 eq_pos = strchr(long_opt_arg, '=');
523 if (eq_pos) {
524 const size_t long_opt_name_size = eq_pos - long_opt_arg;
525
526 /* Isolate the option name */
527 if (long_opt_name_size > max_len) {
528 try_append_string_printf(error,
529 "Invalid argument `--%s`", long_opt_arg);
530 goto error;
531 }
532
533 memcpy(buf, long_opt_arg, long_opt_name_size);
534 buf[long_opt_name_size] = '\0';
535 long_opt_name = buf;
536 }
537
538 /* Find corresponding option descriptor */
539 descr = find_descr(descrs, '\0', long_opt_name);
540 if (!descr) {
541 try_append_string_printf(error, "Unknown option `--%s`",
542 long_opt_name);
543 ret = PARSE_ORIG_ARG_OPT_RET_ERROR_UNKNOWN_OPT;
544 goto error;
545 }
546
547 /* Find option's argument if any */
548 if (descr->with_arg) {
549 if (eq_pos) {
550 /* `--long-opt=arg` style */
551 opt_arg = eq_pos + 1;
552 } else {
553 /* `--long-opt arg` style */
554 if (!next_orig_arg) {
555 try_append_string_printf(error,
556 "Missing required argument for option `--%s`",
557 long_opt_name);
558 goto error;
559 }
560
561 opt_arg = next_orig_arg;
562 used_next_orig_arg = true;
563 }
564 } else if (eq_pos) {
565 /*
566 * Unexpected `--opt=arg` style for a long option which
567 * doesn't accept an argument.
568 */
569 try_append_string_printf(error,
570 "Unexpected argument for option `--%s`", long_opt_name);
571 goto error;
572 }
573
574 /* Create and append option argument */
575 opt_item = create_opt_item(descr, opt_arg);
576 if (!opt_item) {
577 goto error;
578 }
579
580 if (used_next_orig_arg) {
581 iter->i += 2;
582 } else {
583 iter->i++;
584 }
585
586 *item = &opt_item->base;
587 goto end;
588
589error:
590 if (ret == PARSE_ORIG_ARG_OPT_RET_OK) {
591 ret = PARSE_ORIG_ARG_OPT_RET_ERROR;
592 }
593
594end:
595 return ret;
596}
597
598static
599enum parse_orig_arg_opt_ret parse_orig_arg_opt(const char * const orig_arg,
600 const char * const next_orig_arg,
601 const struct argpar_opt_descr * const descrs,
602 struct argpar_iter * const iter, char ** const error,
603 struct argpar_item ** const item)
604{
605 enum parse_orig_arg_opt_ret ret = PARSE_ORIG_ARG_OPT_RET_OK;
606
607 ARGPAR_ASSERT(orig_arg[0] == '-');
608
609 if (orig_arg[1] == '-') {
610 /* Long option */
611 ret = parse_long_opt(&orig_arg[2],
612 next_orig_arg, descrs, iter, error, item);
613 } else {
614 /* Short option */
615 ret = parse_short_opts(&orig_arg[1],
616 next_orig_arg, descrs, iter, error, item);
617 }
618
619 return ret;
620}
621
622static
623bool try_prepend_while_parsing_arg_to_error(char ** const error,
624 const unsigned int i, const char * const arg)
625{
626 char *new_error;
627 bool success;
628
629 if (!error) {
630 success = true;
631 goto end;
632 }
633
634 ARGPAR_ASSERT(*error);
635 new_error = argpar_asprintf("While parsing argument #%u (`%s`): %s",
636 i + 1, arg, *error);
637 if (!new_error) {
638 success = false;
639 goto end;
640 }
641
642 free(*error);
643 *error = new_error;
644 success = true;
645
646end:
647 return success;
648}
649
650ARGPAR_HIDDEN
651struct argpar_iter *argpar_iter_create(const unsigned int argc,
652 const char * const * const argv,
653 const struct argpar_opt_descr * const descrs)
654{
655 struct argpar_iter * const iter = ARGPAR_ZALLOC(struct argpar_iter);
656
657 if (!iter) {
658 goto end;
659 }
660
661 iter->argc = argc;
662 iter->argv = argv;
663 iter->descrs = descrs;
664
665end:
666 return iter;
667}
668
669ARGPAR_HIDDEN
670void argpar_iter_destroy(struct argpar_iter * const iter)
671{
672 free(iter);
673}
674
675ARGPAR_HIDDEN
676enum argpar_iter_parse_next_status argpar_iter_parse_next(
677 struct argpar_iter * const iter,
678 const struct argpar_item ** const item, char ** const error)
679{
680 enum argpar_iter_parse_next_status status;
681 enum parse_orig_arg_opt_ret parse_orig_arg_opt_ret;
682 const char *orig_arg;
683 const char *next_orig_arg;
684
685 ARGPAR_ASSERT(iter->i <= iter->argc);
686
687 if (error) {
688 *error = NULL;
689 }
690
691 if (iter->i == iter->argc) {
692 status = ARGPAR_ITER_PARSE_NEXT_STATUS_END;
693 goto end;
694 }
695
696 orig_arg = iter->argv[iter->i];
697 next_orig_arg =
698 iter->i < (iter->argc - 1) ? iter->argv[iter->i + 1] : NULL;
699
700 if (orig_arg[0] != '-') {
701 /* Non-option argument */
702 struct argpar_item_non_opt * const non_opt_item =
703 create_non_opt_item(orig_arg, iter->i,
704 iter->non_opt_index);
705
706 if (!non_opt_item) {
707 status = ARGPAR_ITER_PARSE_NEXT_STATUS_ERROR;
708 goto end;
709 }
710
711 iter->non_opt_index++;
712 iter->i++;
713 *item = &non_opt_item->base;
714 status = ARGPAR_ITER_PARSE_NEXT_STATUS_OK;
715 goto end;
716 }
717
718 /* Option argument */
719 parse_orig_arg_opt_ret = parse_orig_arg_opt(orig_arg,
720 next_orig_arg, iter->descrs, iter, error,
721 (struct argpar_item **) item);
722 switch (parse_orig_arg_opt_ret) {
723 case PARSE_ORIG_ARG_OPT_RET_OK:
724 status = ARGPAR_ITER_PARSE_NEXT_STATUS_OK;
725 break;
726 case PARSE_ORIG_ARG_OPT_RET_ERROR_UNKNOWN_OPT:
727 try_prepend_while_parsing_arg_to_error(error, iter->i,
728 orig_arg);
729 status = ARGPAR_ITER_PARSE_NEXT_STATUS_ERROR_UNKNOWN_OPT;
730 break;
731 case PARSE_ORIG_ARG_OPT_RET_ERROR:
732 try_prepend_while_parsing_arg_to_error(error, iter->i,
733 orig_arg);
734 status = ARGPAR_ITER_PARSE_NEXT_STATUS_ERROR;
735 break;
736 default:
737 abort();
738 }
739
740end:
741 return status;
742}
743
744ARGPAR_HIDDEN
745unsigned int argpar_iter_get_ingested_orig_args(
746 const struct argpar_iter * const iter)
747{
748 return iter->i;
749}
750
751ARGPAR_HIDDEN
752struct argpar_parse_ret argpar_parse(const unsigned int argc,
753 const char * const * const argv,
754 const struct argpar_opt_descr * const descrs,
755 const bool fail_on_unknown_opt)
756{
757 struct argpar_parse_ret parse_ret = { 0 };
758 const struct argpar_item *item = NULL;
759 struct argpar_iter *iter = NULL;
760
761 parse_ret.items = create_item_array();
762 if (!parse_ret.items) {
763 parse_ret.error = strdup("Failed to create items array.");
764 ARGPAR_ASSERT(parse_ret.error);
765 goto error;
766 }
767
768 iter = argpar_iter_create(argc, argv, descrs);
769 if (!iter) {
770 parse_ret.error = strdup("Failed to create argpar iter.");
771 ARGPAR_ASSERT(parse_ret.error);
772 goto error;
773 }
774
775 while (true) {
776 const enum argpar_iter_parse_next_status status =
777 argpar_iter_parse_next(iter, &item, &parse_ret.error);
778
779 if (status == ARGPAR_ITER_PARSE_NEXT_STATUS_ERROR) {
780 goto error;
781 } else if (status == ARGPAR_ITER_PARSE_NEXT_STATUS_END) {
782 break;
783 } else if (status == ARGPAR_ITER_PARSE_NEXT_STATUS_ERROR_UNKNOWN_OPT) {
784 if (fail_on_unknown_opt) {
785 parse_ret.ingested_orig_args =
786 argpar_iter_get_ingested_orig_args(iter);
787 goto error;
788 }
789
790 free(parse_ret.error);
791 parse_ret.error = NULL;
792 break;
793 }
794
795 ARGPAR_ASSERT(status == ARGPAR_ITER_PARSE_NEXT_STATUS_OK);
796
797 if (!push_item(parse_ret.items, item)) {
798 goto error;
799 }
800
801 item = NULL;
802 }
803
804 ARGPAR_ASSERT(!parse_ret.error);
805 parse_ret.ingested_orig_args = argpar_iter_get_ingested_orig_args(iter);
806 goto end;
807
808error:
809 ARGPAR_ASSERT(parse_ret.error);
810
811 /* That's how we indicate that an error occurred */
812 destroy_item_array(parse_ret.items);
813 parse_ret.items = NULL;
814
815end:
816 argpar_iter_destroy(iter);
817 argpar_item_destroy(item);
818 return parse_ret;
819}
820
821ARGPAR_HIDDEN
822void argpar_parse_ret_fini(struct argpar_parse_ret * const ret)
823{
824 ARGPAR_ASSERT(ret);
825 destroy_item_array(ret->items);
826 ret->items = NULL;
827 free(ret->error);
828 ret->error = NULL;
829}
This page took 0.024159 seconds and 4 git commands to generate.