Make `struct argpar_item` opaque
[argpar.git] / argpar / argpar.c
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 */
39 struct 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 */
67 struct argpar_item {
68 enum argpar_item_type type;
69 };
70
71 /* Option parsing item */
72 struct 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 */
83 struct 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
102 static __attribute__((format(ARGPAR_PRINTF_FORMAT, 1, 0)))
103 char *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
124 end:
125 va_end(args2);
126 return str;
127 }
128
129
130 static __attribute__((format(ARGPAR_PRINTF_FORMAT, 1, 2)))
131 char *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
142 static __attribute__((format(ARGPAR_PRINTF_FORMAT, 2, 3)))
143 bool append_string_printf(char ** const str, const char *fmt, ...)
144 {
145 char *new_str = NULL;
146 char *addendum;
147 bool success;
148 va_list args;
149
150 ARGPAR_ASSERT(str);
151 va_start(args, fmt);
152 addendum = argpar_vasprintf(fmt, args);
153 va_end(args);
154
155 if (!addendum) {
156 success = false;
157 goto end;
158 }
159
160 new_str = argpar_asprintf("%s%s", *str ? *str : "", addendum);
161 if (!new_str) {
162 success = false;
163 goto end;
164 }
165
166 free(*str);
167 *str = new_str;
168 success = true;
169
170 end:
171 free(addendum);
172 return success;
173 }
174
175 ARGPAR_HIDDEN
176 enum argpar_item_type argpar_item_type(const struct argpar_item * const item)
177 {
178 ARGPAR_ASSERT(item);
179 return item->type;
180 }
181
182 ARGPAR_HIDDEN
183 const struct argpar_opt_descr *argpar_item_opt_descr(
184 const struct argpar_item * const item)
185 {
186 ARGPAR_ASSERT(item);
187 ARGPAR_ASSERT(item->type == ARGPAR_ITEM_TYPE_OPT);
188 return ((const struct argpar_item_opt *) item)->descr;
189 }
190
191 ARGPAR_HIDDEN
192 const char *argpar_item_opt_arg(const struct argpar_item * const item)
193 {
194 ARGPAR_ASSERT(item);
195 ARGPAR_ASSERT(item->type == ARGPAR_ITEM_TYPE_OPT);
196 return ((const struct argpar_item_opt *) item)->arg;
197 }
198
199 ARGPAR_HIDDEN
200 const char *argpar_item_non_opt_arg(const struct argpar_item * const item)
201 {
202 ARGPAR_ASSERT(item);
203 ARGPAR_ASSERT(item->type == ARGPAR_ITEM_TYPE_NON_OPT);
204 return ((const struct argpar_item_non_opt *) item)->arg;
205 }
206
207 ARGPAR_HIDDEN
208 unsigned int argpar_item_non_opt_orig_index(
209 const struct argpar_item * const item)
210 {
211 ARGPAR_ASSERT(item);
212 ARGPAR_ASSERT(item->type == ARGPAR_ITEM_TYPE_NON_OPT);
213 return ((const struct argpar_item_non_opt *) item)->orig_index;
214 }
215
216 ARGPAR_HIDDEN
217 unsigned int argpar_item_non_opt_non_opt_index(
218 const struct argpar_item * const item)
219 {
220 ARGPAR_ASSERT(item);
221 ARGPAR_ASSERT(item->type == ARGPAR_ITEM_TYPE_NON_OPT);
222 return ((const struct argpar_item_non_opt *) item)->non_opt_index;
223 }
224
225 ARGPAR_HIDDEN
226 void argpar_item_destroy(const struct argpar_item * const item)
227 {
228 if (!item) {
229 goto end;
230 }
231
232 if (item->type == ARGPAR_ITEM_TYPE_OPT) {
233 struct argpar_item_opt * const opt_item =
234 (struct argpar_item_opt *) item;
235
236 free(opt_item->arg);
237 }
238
239 free((void *) item);
240
241 end:
242 return;
243 }
244
245 static
246 bool push_item(struct argpar_item_array * const array,
247 const struct argpar_item * const item)
248 {
249 bool success;
250
251 ARGPAR_ASSERT(array);
252 ARGPAR_ASSERT(item);
253
254 if (array->n_items == array->n_alloc) {
255 const unsigned int new_n_alloc = array->n_alloc * 2;
256 const struct argpar_item ** const new_items =
257 ARGPAR_REALLOC(array->items, const struct argpar_item *,
258 new_n_alloc);
259 if (!new_items) {
260 success = false;
261 goto end;
262 }
263
264 array->n_alloc = new_n_alloc;
265 array->items = new_items;
266 }
267
268 array->items[array->n_items] = item;
269 array->n_items++;
270 success = true;
271
272 end:
273 return success;
274 }
275
276 static
277 void destroy_item_array(struct argpar_item_array * const array)
278 {
279 if (array) {
280 unsigned int i;
281
282 for (i = 0; i < array->n_items; i++) {
283 argpar_item_destroy(array->items[i]);
284 }
285
286 free(array->items);
287 free(array);
288 }
289 }
290
291 static
292 struct argpar_item_array *create_item_array(void)
293 {
294 struct argpar_item_array *ret;
295 const int initial_size = 10;
296
297 ret = ARGPAR_ZALLOC(struct argpar_item_array);
298 if (!ret) {
299 goto end;
300 }
301
302 ret->items = ARGPAR_CALLOC(const struct argpar_item *, initial_size);
303 if (!ret->items) {
304 goto error;
305 }
306
307 ret->n_alloc = initial_size;
308 goto end;
309
310 error:
311 destroy_item_array(ret);
312 ret = NULL;
313
314 end:
315 return ret;
316 }
317
318 static
319 struct argpar_item_opt *create_opt_item(
320 const struct argpar_opt_descr * const descr,
321 const char * const arg)
322 {
323 struct argpar_item_opt *opt_item =
324 ARGPAR_ZALLOC(struct argpar_item_opt);
325
326 if (!opt_item) {
327 goto end;
328 }
329
330 opt_item->base.type = ARGPAR_ITEM_TYPE_OPT;
331 opt_item->descr = descr;
332
333 if (arg) {
334 opt_item->arg = strdup(arg);
335 if (!opt_item->arg) {
336 goto error;
337 }
338 }
339
340 goto end;
341
342 error:
343 argpar_item_destroy(&opt_item->base);
344 opt_item = NULL;
345
346 end:
347 return opt_item;
348 }
349
350 static
351 struct argpar_item_non_opt *create_non_opt_item(const char * const arg,
352 const unsigned int orig_index,
353 const unsigned int non_opt_index)
354 {
355 struct argpar_item_non_opt * const non_opt_item =
356 ARGPAR_ZALLOC(struct argpar_item_non_opt);
357
358 if (!non_opt_item) {
359 goto end;
360 }
361
362 non_opt_item->base.type = ARGPAR_ITEM_TYPE_NON_OPT;
363 non_opt_item->arg = arg;
364 non_opt_item->orig_index = orig_index;
365 non_opt_item->non_opt_index = non_opt_index;
366
367 end:
368 return non_opt_item;
369 }
370
371 static
372 const struct argpar_opt_descr *find_descr(
373 const struct argpar_opt_descr * const descrs,
374 const char short_name, const char * const long_name)
375 {
376 const struct argpar_opt_descr *descr;
377
378 for (descr = descrs; descr->short_name || descr->long_name; descr++) {
379 if (short_name && descr->short_name &&
380 short_name == descr->short_name) {
381 goto end;
382 }
383
384 if (long_name && descr->long_name &&
385 strcmp(long_name, descr->long_name) == 0) {
386 goto end;
387 }
388 }
389
390 end:
391 return !descr->short_name && !descr->long_name ? NULL : descr;
392 }
393
394 enum parse_orig_arg_opt_ret {
395 PARSE_ORIG_ARG_OPT_RET_OK,
396 PARSE_ORIG_ARG_OPT_RET_ERROR_UNKNOWN_OPT = -2,
397 PARSE_ORIG_ARG_OPT_RET_ERROR = -1,
398 };
399
400 static
401 enum parse_orig_arg_opt_ret parse_short_opts(const char * const short_opts,
402 const char * const next_orig_arg,
403 const struct argpar_opt_descr * const descrs,
404 struct argpar_iter * const iter,
405 char ** const error, struct argpar_item ** const item)
406 {
407 enum parse_orig_arg_opt_ret ret = PARSE_ORIG_ARG_OPT_RET_OK;
408 bool used_next_orig_arg = false;
409 const char *opt_arg = NULL;
410 const struct argpar_opt_descr *descr;
411 struct argpar_item_opt *opt_item;
412
413 if (strlen(short_opts) == 0) {
414 append_string_printf(error, "Invalid argument");
415 goto error;
416 }
417
418 if (!iter->short_opt_ch) {
419 iter->short_opt_ch = short_opts;
420 }
421
422 /* Find corresponding option descriptor */
423 descr = find_descr(descrs, *iter->short_opt_ch, NULL);
424 if (!descr) {
425 ret = PARSE_ORIG_ARG_OPT_RET_ERROR_UNKNOWN_OPT;
426 append_string_printf(error, "Unknown option `-%c`",
427 *iter->short_opt_ch);
428 goto error;
429 }
430
431 if (descr->with_arg) {
432 if (iter->short_opt_ch[1]) {
433 /* `-oarg` form */
434 opt_arg = &iter->short_opt_ch[1];
435 } else {
436 /* `-o arg` form */
437 opt_arg = next_orig_arg;
438 used_next_orig_arg = true;
439 }
440
441 /*
442 * We accept `-o ''` (empty option argument), but not
443 * `-o` alone if an option argument is expected.
444 */
445 if (!opt_arg || (iter->short_opt_ch[1] &&
446 strlen(opt_arg) == 0)) {
447 append_string_printf(error,
448 "Missing required argument for option `-%c`",
449 *iter->short_opt_ch);
450 used_next_orig_arg = false;
451 goto error;
452 }
453 }
454
455 /* Create and append option argument */
456 opt_item = create_opt_item(descr, opt_arg);
457 if (!opt_item) {
458 goto error;
459 }
460
461 *item = &opt_item->base;
462 iter->short_opt_ch++;
463
464 if (descr->with_arg || !*iter->short_opt_ch) {
465 /* Option has an argument: no more options */
466 iter->short_opt_ch = NULL;
467
468 if (used_next_orig_arg) {
469 iter->i += 2;
470 } else {
471 iter->i++;
472 }
473 }
474
475 goto end;
476
477 error:
478 if (ret == PARSE_ORIG_ARG_OPT_RET_OK) {
479 ret = PARSE_ORIG_ARG_OPT_RET_ERROR;
480 }
481
482 end:
483 return ret;
484 }
485
486 static
487 enum parse_orig_arg_opt_ret parse_long_opt(const char * const long_opt_arg,
488 const char * const next_orig_arg,
489 const struct argpar_opt_descr * const descrs,
490 struct argpar_iter * const iter,
491 char ** const error, struct argpar_item ** const item)
492 {
493 const size_t max_len = 127;
494 enum parse_orig_arg_opt_ret ret = PARSE_ORIG_ARG_OPT_RET_OK;
495 const struct argpar_opt_descr *descr;
496 struct argpar_item_opt *opt_item;
497 bool used_next_orig_arg = false;
498
499 /* Option's argument, if any */
500 const char *opt_arg = NULL;
501
502 /* Position of first `=`, if any */
503 const char *eq_pos;
504
505 /* Buffer holding option name when `long_opt_arg` contains `=` */
506 char buf[max_len + 1];
507
508 /* Option name */
509 const char *long_opt_name = long_opt_arg;
510
511 if (strlen(long_opt_arg) == 0) {
512 append_string_printf(error, "Invalid argument");
513 goto error;
514 }
515
516 /* Find the first `=` in original argument */
517 eq_pos = strchr(long_opt_arg, '=');
518 if (eq_pos) {
519 const size_t long_opt_name_size = eq_pos - long_opt_arg;
520
521 /* Isolate the option name */
522 if (long_opt_name_size > max_len) {
523 append_string_printf(error, "Invalid argument `--%s`",
524 long_opt_arg);
525 goto error;
526 }
527
528 memcpy(buf, long_opt_arg, long_opt_name_size);
529 buf[long_opt_name_size] = '\0';
530 long_opt_name = buf;
531 }
532
533 /* Find corresponding option descriptor */
534 descr = find_descr(descrs, '\0', long_opt_name);
535 if (!descr) {
536 append_string_printf(error, "Unknown option `--%s`",
537 long_opt_name);
538 ret = PARSE_ORIG_ARG_OPT_RET_ERROR_UNKNOWN_OPT;
539 goto error;
540 }
541
542 /* Find option's argument if any */
543 if (descr->with_arg) {
544 if (eq_pos) {
545 /* `--long-opt=arg` style */
546 opt_arg = eq_pos + 1;
547 } else {
548 /* `--long-opt arg` style */
549 if (!next_orig_arg) {
550 append_string_printf(error,
551 "Missing required argument for option `--%s`",
552 long_opt_name);
553 goto error;
554 }
555
556 opt_arg = next_orig_arg;
557 used_next_orig_arg = true;
558 }
559 } else if (eq_pos) {
560 /*
561 * Unexpected `--opt=arg` style for a long option which
562 * doesn't accept an argument.
563 */
564 append_string_printf(error,
565 "Unexpected argument for option `--%s`", long_opt_name);
566 goto error;
567 }
568
569 /* Create and append option argument */
570 opt_item = create_opt_item(descr, opt_arg);
571 if (!opt_item) {
572 goto error;
573 }
574
575 if (used_next_orig_arg) {
576 iter->i += 2;
577 } else {
578 iter->i++;
579 }
580
581 *item = &opt_item->base;
582 goto end;
583
584 error:
585 if (ret == PARSE_ORIG_ARG_OPT_RET_OK) {
586 ret = PARSE_ORIG_ARG_OPT_RET_ERROR;
587 }
588
589 end:
590 return ret;
591 }
592
593 static
594 enum parse_orig_arg_opt_ret parse_orig_arg_opt(const char * const orig_arg,
595 const char * const next_orig_arg,
596 const struct argpar_opt_descr * const descrs,
597 struct argpar_iter * const iter, char ** const error,
598 struct argpar_item ** const item)
599 {
600 enum parse_orig_arg_opt_ret ret = PARSE_ORIG_ARG_OPT_RET_OK;
601
602 ARGPAR_ASSERT(orig_arg[0] == '-');
603
604 if (orig_arg[1] == '-') {
605 /* Long option */
606 ret = parse_long_opt(&orig_arg[2],
607 next_orig_arg, descrs, iter, error, item);
608 } else {
609 /* Short option */
610 ret = parse_short_opts(&orig_arg[1],
611 next_orig_arg, descrs, iter, error, item);
612 }
613
614 return ret;
615 }
616
617 static
618 bool prepend_while_parsing_arg_to_error(char ** const error,
619 const unsigned int i, const char * const arg)
620 {
621 char *new_error;
622 bool success;
623
624 ARGPAR_ASSERT(error);
625 ARGPAR_ASSERT(*error);
626 new_error = argpar_asprintf("While parsing argument #%u (`%s`): %s",
627 i + 1, arg, *error);
628 if (!new_error) {
629 success = false;
630 goto end;
631 }
632
633 free(*error);
634 *error = new_error;
635 success = true;
636
637 end:
638 return success;
639 }
640
641 ARGPAR_HIDDEN
642 struct argpar_iter *argpar_iter_create(const unsigned int argc,
643 const char * const * const argv,
644 const struct argpar_opt_descr * const descrs)
645 {
646 struct argpar_iter * const iter = ARGPAR_ZALLOC(struct argpar_iter);
647
648 if (!iter) {
649 goto end;
650 }
651
652 iter->argc = argc;
653 iter->argv = argv;
654 iter->descrs = descrs;
655
656 end:
657 return iter;
658 }
659
660 ARGPAR_HIDDEN
661 void argpar_iter_destroy(struct argpar_iter * const iter)
662 {
663 free(iter);
664 }
665
666 ARGPAR_HIDDEN
667 enum argpar_iter_parse_next_status argpar_iter_parse_next(
668 struct argpar_iter * const iter,
669 const struct argpar_item ** const item, char ** const error)
670 {
671 enum argpar_iter_parse_next_status status;
672 enum parse_orig_arg_opt_ret parse_orig_arg_opt_ret;
673 const char *orig_arg;
674 const char *next_orig_arg;
675
676 ARGPAR_ASSERT(iter->i <= iter->argc);
677 *error = NULL;
678
679 if (iter->i == iter->argc) {
680 status = ARGPAR_ITER_PARSE_NEXT_STATUS_END;
681 goto end;
682 }
683
684 orig_arg = iter->argv[iter->i];
685 next_orig_arg =
686 iter->i < (iter->argc - 1) ? iter->argv[iter->i + 1] : NULL;
687
688 if (orig_arg[0] != '-') {
689 /* Non-option argument */
690 struct argpar_item_non_opt * const non_opt_item =
691 create_non_opt_item(orig_arg, iter->i,
692 iter->non_opt_index);
693
694 if (!non_opt_item) {
695 status = ARGPAR_ITER_PARSE_NEXT_STATUS_ERROR;
696 goto end;
697 }
698
699 iter->non_opt_index++;
700 iter->i++;
701 *item = &non_opt_item->base;
702 status = ARGPAR_ITER_PARSE_NEXT_STATUS_OK;
703 goto end;
704 }
705
706 /* Option argument */
707 parse_orig_arg_opt_ret = parse_orig_arg_opt(orig_arg,
708 next_orig_arg, iter->descrs, iter, error,
709 (struct argpar_item **) item);
710 switch (parse_orig_arg_opt_ret) {
711 case PARSE_ORIG_ARG_OPT_RET_OK:
712 status = ARGPAR_ITER_PARSE_NEXT_STATUS_OK;
713 break;
714 case PARSE_ORIG_ARG_OPT_RET_ERROR_UNKNOWN_OPT:
715 prepend_while_parsing_arg_to_error(error, iter->i, orig_arg);
716 status = ARGPAR_ITER_PARSE_NEXT_STATUS_ERROR_UNKNOWN_OPT;
717 break;
718 case PARSE_ORIG_ARG_OPT_RET_ERROR:
719 prepend_while_parsing_arg_to_error(error, iter->i, orig_arg);
720 status = ARGPAR_ITER_PARSE_NEXT_STATUS_ERROR;
721 break;
722 default:
723 abort();
724 }
725
726 end:
727 return status;
728 }
729
730 ARGPAR_HIDDEN
731 unsigned int argpar_iter_get_ingested_orig_args(
732 const struct argpar_iter * const iter)
733 {
734 return iter->i;
735 }
736
737 ARGPAR_HIDDEN
738 struct argpar_parse_ret argpar_parse(const unsigned int argc,
739 const char * const * const argv,
740 const struct argpar_opt_descr * const descrs,
741 const bool fail_on_unknown_opt)
742 {
743 struct argpar_parse_ret parse_ret = { 0 };
744 const struct argpar_item *item = NULL;
745 struct argpar_iter *iter = NULL;
746
747 parse_ret.items = create_item_array();
748 if (!parse_ret.items) {
749 parse_ret.error = strdup("Failed to create items array.");
750 ARGPAR_ASSERT(parse_ret.error);
751 goto error;
752 }
753
754 iter = argpar_iter_create(argc, argv, descrs);
755 if (!iter) {
756 parse_ret.error = strdup("Failed to create argpar iter.");
757 ARGPAR_ASSERT(parse_ret.error);
758 goto error;
759 }
760
761 while (true) {
762 const enum argpar_iter_parse_next_status status =
763 argpar_iter_parse_next(iter, &item, &parse_ret.error);
764
765 if (status == ARGPAR_ITER_PARSE_NEXT_STATUS_ERROR) {
766 goto error;
767 } else if (status == ARGPAR_ITER_PARSE_NEXT_STATUS_END) {
768 break;
769 } else if (status == ARGPAR_ITER_PARSE_NEXT_STATUS_ERROR_UNKNOWN_OPT) {
770 if (fail_on_unknown_opt) {
771 parse_ret.ingested_orig_args =
772 argpar_iter_get_ingested_orig_args(iter);
773 goto error;
774 }
775
776 free(parse_ret.error);
777 parse_ret.error = NULL;
778 break;
779 }
780
781 ARGPAR_ASSERT(status == ARGPAR_ITER_PARSE_NEXT_STATUS_OK);
782
783 if (!push_item(parse_ret.items, item)) {
784 goto error;
785 }
786
787 item = NULL;
788 }
789
790 ARGPAR_ASSERT(!parse_ret.error);
791 parse_ret.ingested_orig_args = argpar_iter_get_ingested_orig_args(iter);
792 goto end;
793
794 error:
795 ARGPAR_ASSERT(parse_ret.error);
796
797 /* That's how we indicate that an error occurred */
798 destroy_item_array(parse_ret.items);
799 parse_ret.items = NULL;
800
801 end:
802 argpar_iter_destroy(iter);
803 argpar_item_destroy(item);
804 return parse_ret;
805 }
806
807 ARGPAR_HIDDEN
808 void argpar_parse_ret_fini(struct argpar_parse_ret * const ret)
809 {
810 ARGPAR_ASSERT(ret);
811 destroy_item_array(ret->items);
812 ret->items = NULL;
813 free(ret->error);
814 ret->error = NULL;
815 }
This page took 0.04393 seconds and 5 git commands to generate.