Fix and improve error reporting
[ctxopt.git] / ctxopt.c
blob1981d9653d7e0b6c237b4de2a2411a50df4c5f98
1 /* ################################################################### */
2 /* This Source Code Form is subject to the terms of the Mozilla Public */
3 /* License, v. 2.0. If a copy of the MPL was not distributed with this */
4 /* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
5 /* ################################################################### */
7 #include <errno.h>
8 #include <limits.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <unistd.h>
12 #include <ctype.h>
13 #include <sys/types.h>
14 #include <regex.h>
15 #include <stdarg.h>
16 #include <string.h>
17 #include "ctxopt.h"
19 /* ************************ */
20 /* Static global variables. */
21 /* ************************ */
23 static void * contexts_bst;
24 static void * options_bst;
26 state_t * cur_state;
28 /* Prototypes */
30 /* ************************** */
31 /* Fatal messages prototypes. */
32 /* ************************** */
34 static void (**err_functions)(errors e, state_t * state);
36 static void
37 fatal_internal(const char * format, ...);
39 static void
40 fatal(errors e, char * errmsg);
42 static int user_rc; /* Used by various callback functions */
43 static int user_value; /* Used by various callback functions */
44 static char * user_string; /* Used by various callback functions */
45 static char * user_string2; /* Used by various callback functions */
46 static void * user_object; /* Used by various callback functions */
48 /* ************************************ */
49 /* Memory management static prototypes. */
50 /* ************************************ */
52 static void *
53 xmalloc(size_t size);
55 static void *
56 xcalloc(size_t num, size_t size);
58 static void *
59 xrealloc(void * ptr, size_t size);
61 static char *
62 xstrdup(const char * p);
64 static char *
65 xstrndup(const char * str, size_t len);
67 /* ********************** */
68 /* BST static prototypes. */
69 /* ********************** */
71 typedef struct bst_s bst_t;
73 typedef enum
75 preorder,
76 postorder,
77 endorder,
78 leaf
79 } walk_order_e;
81 #if 0 /* Unused yet */
82 static void *
83 bst_delete(const void * vkey, void ** vrootp,
84 int (*compar)(const void *, const void *));
85 #endif
87 static void
88 bst_destroy(void * vrootp, void (*clean)(void *));
90 static void *
91 bst_find(const void * vkey, void * const * vrootp,
92 int (*compar)(const void *, const void *));
94 static void *
95 bst_search(void * vkey, void ** vrootp,
96 int (*compar)(const void *, const void *));
98 static void
99 bst_walk_recurse(const bst_t * root,
100 void (*action)(const void *, walk_order_e, int), int level);
102 static void
103 bst_walk(const void * vroot, void (*action)(const void *, walk_order_e, int));
105 /* ****************************** */
106 /* Linked list static prototypes. */
107 /* ****************************** */
109 typedef struct ll_node_s ll_node_t;
110 typedef struct ll_s ll_t;
112 static void
113 ll_append(ll_t * const list, void * const data);
115 static void
116 ll_prepend(ll_t * const list, void * const data);
118 static void
119 ll_insert_after(ll_t * const list, ll_node_t * node, void * const data);
121 static void
122 ll_insert_before(ll_t * const list, ll_node_t * node, void * const data);
124 static int
125 ll_delete(ll_t * const list, ll_node_t * node);
127 #if 0 /* Unused yet */
128 static ll_node_t *
129 ll_find(ll_t * const, void * const, int (*)(const void *, const void *));
130 #endif
132 static void
133 ll_init(ll_t * list);
135 static ll_node_t *
136 ll_new_node(void);
138 static ll_t *
139 ll_new(void);
141 static void
142 ll_free(ll_t * const list, void (*)(void *));
144 static void
145 ll_destroy(ll_t * const list, void (*)(void *));
147 static int
148 ll_strarray(ll_t * list, ll_node_t * start_node, int * count, char *** array);
150 /* ************************** */
151 /* Various static prototypes. */
152 /* ************************** */
154 static void
155 ltrim(char * str, const char * trim_str);
157 static void
158 rtrim(char * str, const char * trim_str, size_t min);
160 static int
161 strchrcount(char * str, char c);
163 static int
164 strpref(char * s1, char * s2);
166 static int
167 stricmp(const char * s1, const char * s2);
169 static char *
170 xstrtok_r(char * str, const char * delim, char ** end);
172 static int
173 eval_yes(char * value, int * invalid);
175 static char *
176 get_word(char * str, char * buf, size_t len);
178 /* ************************* */
179 /* ctxopt static prototypes. */
180 /* ************************* */
182 typedef struct flags_s flags_t;
183 typedef struct opt_s opt_t;
184 typedef struct par_s par_t;
185 typedef struct ctx_s ctx_t;
186 typedef struct constraint_s constraint_t;
187 typedef struct ctx_inst_s ctx_inst_t;
188 typedef struct opt_inst_s opt_inst_t;
189 typedef struct seen_opt_s seen_opt_t;
191 static char *
192 strtoken(char * s, char * token, size_t tok_len, char * pattern, int * pos);
194 static int
195 ctx_compare(const void * c1, const void * c2);
197 static void
198 ctx_free(void * o);
200 static void
201 ctx_inst_free(void * ci);
203 static void
204 opt_inst_free(void * oi);
206 static int
207 seen_opt_compare(const void * so1, const void * so2);
209 static void
210 incomp_bst_free(void * b);
212 static void
213 seen_opt_free(void * seen_opt);
215 static int
216 opt_compare(const void * o1, const void * o2);
218 static void
219 opt_free(void * o);
221 static int
222 par_compare(const void * a1, const void * a2);
224 static void
225 par_free(void * p);
227 static void
228 constraint_free(void * cstr);
230 static ctx_t *
231 locate_ctx(char * name);
233 static opt_t *
234 locate_opt(char * name);
236 static par_t *
237 locate_par(char * name, ctx_t * ctx);
239 static void
240 print_options(ll_t * list, int * has_optional, int * has_ellipsis,
241 int * has_rule, int * has_generic_arg, int * has_ctx_change,
242 int * has_early_eval);
243 static void
244 print_explanations(int has_early_eval, int has_ctx_change, int has_generic_arg,
245 int has_optional, int has_ellipsis, int has_rule);
246 static void
247 bst_seen_opt_cb(const void * node, walk_order_e kind, int level);
249 static void
250 bst_seen_opt_seen_cb(const void * node, walk_order_e kind, int level);
252 static void
253 bst_print_ctx_cb(const void * node, walk_order_e kind, int level);
255 static void
256 bst_check_opt_cb(const void * node, walk_order_e kind, int level);
258 static void
259 bst_match_par_cb(const void * node, walk_order_e kind, int level);
261 static void
262 match_prefix_cb(const void * node, walk_order_e kind, int level);
264 static int
265 has_unseen_mandatory_opt(ctx_inst_t * ctx_inst, char ** missing);
267 static int
268 opt_parse(char * s, opt_t ** opt);
270 static int
271 init_opts(char * spec, ctx_t * ctx);
273 static int
274 ctxopt_build_cmdline_list(int nb_words, char ** words);
276 static int
277 opt_set_parms(char * opt_name, char * par_str);
279 static ctx_inst_t *
280 new_ctx_inst(ctx_t * ctx, ctx_inst_t * prev_ctx_inst);
282 static void
283 evaluate_ctx_inst(ctx_inst_t * ctx_inst);
285 /* ****************************** */
286 /* Fatal messages implementation. */
287 /* ****************************** */
289 /* ================================================================== */
290 /* Fatal error function used when a fatal condition is encountered. */
291 /* This function is reserved for the ctxopt internal usage. */
292 /* */
293 /* format : printf like format */
294 /* ... : remaining arguments interpreted using the format argument */
295 /* ================================================================== */
296 static void
297 fatal_internal(const char * format, ...)
299 va_list args;
301 fprintf(stderr, "CTXOPT: ");
303 va_start(args, format);
304 vfprintf(stderr, format, args);
305 fprintf(stderr, "\n");
306 va_end(args);
308 exit(EXIT_FAILURE);
311 /* ====================================================================== */
312 /* Generic fatal error function. This one uses the global status ctxopt */
313 /* stored in the cur_state structure and can call custom error functions. */
314 /* registered by the users for a given error identifier if any. */
315 /* */
316 /* e : Error identifier responsible of the fatal error */
317 /* errmsg : Users's provided string specific to the error e */
318 /* Note that errmsg is not used in all cases */
319 /* */
320 /* CTXOPTMISPAR Missing parameter */
321 /* CTXOPTMISARG Missing argument */
322 /* CTXOPTUXPARG Unexpected argument */
323 /* CTXOPTDUPOPT Duplicated option */
324 /* CTXOPTUNKPAR Unknown parameter */
325 /* CTXOPTINCOPT Incompatible option */
326 /* CTXOPTCTEOPT Option: bad number of occurrences */
327 /* CTXOPTCTLOPT Option: not enough occurrences */
328 /* CTXOPTCTGOPT Option: too many occurrence of */
329 /* CTXOPTCTEARG Arguments: bad number of occurrences */
330 /* CTXOPTCTLARG Arguments: not enough occurrences */
331 /* CTXOPTCTGARG Arguments: too many occurrences */
332 /* ====================================================================== */
333 static void
334 fatal(errors e, char * errmsg)
336 if (err_functions[e] != NULL)
337 err_functions[e](e, cur_state);
338 else
340 switch (e)
342 case CTXOPTNOERR:
343 break;
345 case CTXOPTMISPAR:
346 if (cur_state->ctx_par_name != NULL)
347 fprintf(stderr,
348 "the mandatory parameter(s) %s are missing in the context "
349 "introduced by %s.\n",
350 errmsg, cur_state->ctx_par_name);
351 else
352 fprintf(stderr,
353 "The mandatory parameter(s) %s are missing "
354 "in the main context.\n",
355 errmsg);
357 free(errmsg);
358 break;
360 case CTXOPTUNXARG:
361 fprintf(stderr,
362 "The parameter %s takes no arguments "
363 "or has too many arguments.\n",
364 cur_state->cur_opt_par_name);
365 break;
367 case CTXOPTMISARG:
368 if (cur_state->pre_opt_par_name != NULL)
369 fprintf(stderr, "%s requires argument(s).\n",
370 cur_state->pre_opt_par_name);
371 else
372 fprintf(stderr, "%s requires argument(s).\n",
373 cur_state->cur_opt_par_name);
374 break;
376 case CTXOPTDUPOPT:
377 if (cur_state->pre_opt_par_name != NULL)
378 fprintf(stderr,
379 "The parameter %s can only appear once in the context "
380 "introduced by %s.\n",
381 cur_state->cur_opt_params, cur_state->ctx_par_name);
382 else
383 fprintf(stderr,
384 "The parameter %s can only appear once "
385 "in the main context.\n",
386 cur_state->cur_opt_params);
387 break;
389 case CTXOPTUNKPAR:
390 fprintf(stderr, "Unknown parameter %s.\n", cur_state->cur_opt_par_name);
391 break;
393 case CTXOPTINCOPT:
394 fprintf(stderr, "The parameter %s is incompatible with %s.\n",
395 cur_state->cur_opt_par_name, errmsg);
396 break;
398 case CTXOPTCTEOPT:
399 if (cur_state->ctx_par_name)
400 fprintf(stderr,
401 "The parameter %s must appear exactly %d times "
402 "in the context introduced by %s.\n",
403 cur_state->cur_opt_params, cur_state->opts_count,
404 cur_state->ctx_par_name);
405 else
406 fprintf(stderr,
407 "The parameter %s must appear exactly %d times "
408 "in the main context.\n",
409 cur_state->cur_opt_params, cur_state->opts_count);
410 break;
412 case CTXOPTCTLOPT:
413 if (cur_state->ctx_par_name)
414 fprintf(stderr,
415 "The parameter %s must appear less than %d times "
416 "in the context introduced by %s.\n",
417 cur_state->cur_opt_params, cur_state->opts_count,
418 cur_state->ctx_par_name);
419 else
420 fprintf(stderr,
421 "The parameter %s must appear less than %d times "
422 "in the main context.\n",
423 cur_state->cur_opt_params, cur_state->opts_count);
424 break;
426 case CTXOPTCTGOPT:
427 if (cur_state->ctx_par_name)
428 fprintf(stderr,
429 "The parameter %s must appear more than %d times "
430 "in the context introduced by %s.\n",
431 cur_state->cur_opt_params, cur_state->opts_count,
432 cur_state->ctx_par_name);
433 else
434 fprintf(stderr,
435 "The parameter %s must appear more than %d times "
436 "in the main context.\n",
437 cur_state->cur_opt_params, cur_state->opts_count);
438 break;
440 case CTXOPTCTEARG:
441 fprintf(stderr, "The parameter %s must have exactly %d arguments.\n",
442 cur_state->cur_opt_par_name, cur_state->opt_args_count);
443 break;
445 case CTXOPTCTLARG:
446 fprintf(stderr, "The parameter %s must have less than %d arguments.\n",
447 cur_state->cur_opt_par_name, cur_state->opt_args_count);
448 break;
450 case CTXOPTCTGARG:
451 fprintf(stderr, "The parameter %s must have more than %d arguments.\n",
452 cur_state->cur_opt_par_name, cur_state->opt_args_count);
453 break;
455 case CTXOPTERRSIZ:
456 break;
460 ctxopt_ctx_disp_usage(cur_state->ctx_name, continue_after);
462 exit(e); /* Exit with the error id e as return code. */
465 /* ********************************* */
466 /* Memory management implementation. */
467 /* ********************************* */
469 /* ================== */
470 /* Customized malloc. */
471 /* ================== */
472 static void *
473 xmalloc(size_t size)
475 void * allocated;
476 size_t real_size;
478 real_size = (size > 0) ? size : 1;
479 allocated = malloc(real_size);
480 if (allocated == NULL)
481 fatal_internal("Insufficient memory (attempt to malloc %lu bytes).\n",
482 (unsigned long int)size);
484 return allocated;
487 /* ================== */
488 /* Customized calloc. */
489 /* ================== */
490 static void *
491 xcalloc(size_t n, size_t size)
493 void * allocated;
495 n = (n > 0) ? n : 1;
496 size = (size > 0) ? size : 1;
497 allocated = calloc(n, size);
498 if (allocated == NULL)
499 fatal_internal("Insufficient memory (attempt to calloc %lu bytes).\n",
500 (unsigned long int)size);
502 return allocated;
505 /* =================== */
506 /* Customized realloc. */
507 /* =================== */
508 static void *
509 xrealloc(void * p, size_t size)
511 void * allocated;
513 allocated = realloc(p, size);
514 if (allocated == NULL && size > 0)
515 fatal_internal("Insufficient memory (attempt to xrealloc %lu bytes).\n",
516 (unsigned long int)size);
518 return allocated;
521 /* ==================================== */
522 /* strdup implementation using xmalloc. */
523 /* ==================================== */
524 static char *
525 xstrdup(const char * p)
527 char * allocated;
529 allocated = xmalloc(strlen(p) + 1);
530 strcpy(allocated, p);
532 return allocated;
535 /* =================================================== */
536 /* strndup implementation using xmalloc. */
537 /* This version guarantees that there is a final '\0'. */
538 /* =================================================== */
539 static char *
540 xstrndup(const char * str, size_t len)
542 char * p;
544 p = memchr(str, '\0', len);
546 if (p)
547 len = p - str;
549 p = xmalloc(len + 1);
550 memcpy(p, str, len);
551 p[len] = '\0';
553 return p;
556 /* *************************** */
557 /* Linked list implementation. */
558 /* *************************** */
560 /* Linked list node structure. */
561 /* """"""""""""""""""""""""""" */
562 struct ll_node_s
564 void * data;
565 struct ll_node_s * next;
566 struct ll_node_s * prev;
569 /* Linked List structure. */
570 /* """""""""""""""""""""" */
571 struct ll_s
573 ll_node_t * head;
574 ll_node_t * tail;
575 long len;
578 /* ========================= */
579 /* Create a new linked list. */
580 /* ========================= */
581 static ll_t *
582 ll_new(void)
584 ll_t * ret = xmalloc(sizeof(ll_t));
585 ll_init(ret);
587 return ret;
590 /* =============================================== */
591 /* Free all the elements of a list (make it empty) */
592 /* NULL or a custom function may be used to free */
593 /* the sub components of the elements. */
594 /* =============================================== */
595 static void
596 ll_free(ll_t * const list, void (*clean)(void *))
598 if (list)
599 while (list->head)
601 /* Apply a custom cleaner if not NULL. */
602 /* """"""""""""""""""""""""""""""""""" */
603 if (clean)
604 clean(list->head->data);
606 ll_delete(list, list->head);
610 /* ==================================== */
611 /* Destroy a list and all its elements. */
612 /* ==================================== */
613 static void
614 ll_destroy(ll_t * list, void (*clean)(void *))
616 if (list)
618 ll_free(list, clean);
619 free(list);
623 /* ========================= */
624 /* Initialize a linked list. */
625 /* ========================= */
626 static void
627 ll_init(ll_t * list)
629 list->head = NULL;
630 list->tail = NULL;
631 list->len = 0;
634 /* ===================================================== */
635 /* Allocate the space for a new node in the linked list. */
636 /* ===================================================== */
637 static ll_node_t *
638 ll_new_node(void)
640 ll_node_t * ret = xmalloc(sizeof(ll_node_t));
642 return ret;
645 /* ==================================================================== */
646 /* Append a new node filled with its data at the end of the linked list */
647 /* The user is responsible for the memory management of the data. */
648 /* ==================================================================== */
649 static void
650 ll_append(ll_t * const list, void * const data)
652 ll_node_t * node;
654 node = ll_new_node(); /* ll_new_node cannot return NULL because it *
655 | uses xmalloc which does not return if there *
656 | is an allocation error. */
658 node->data = data;
659 node->next = NULL;
661 node->prev = list->tail;
662 if (list->tail)
663 list->tail->next = node;
664 else
665 list->head = node;
667 list->tail = node;
669 ++list->len;
672 /* ================================================================== */
673 /* Put a new node filled with its data at the beginning of the linked */
674 /* list. */
675 /* The user is responsible for the memory management of the data. */
676 /* ================================================================== */
677 static void
678 ll_prepend(ll_t * const list, void * const data)
680 ll_node_t * node;
682 node = ll_new_node(); /* ll_new_node cannot return NULL because it *
683 | uses xmalloc which does not return if there *
684 | is an allocation error. */
686 node->data = data;
687 node->prev = NULL;
689 node->next = list->head;
690 if (list->head)
691 list->head->prev = node;
692 else
693 list->tail = node;
695 list->head = node;
697 ++list->len;
700 /* ======================================================== */
701 /* Insert a new node before the specified node in the list. */
702 /* ======================================================== */
703 static void
704 ll_insert_before(ll_t * const list, ll_node_t * node, void * const data)
706 ll_node_t * new_node;
708 if (node->prev == NULL)
709 ll_prepend(list, data);
710 else
712 new_node = ll_new_node(); /* ll_new_node cannot return NULL because it *
713 | uses xmalloc which does not return if there *
714 | is an allocation error. */
716 new_node->data = data;
717 new_node->next = node;
718 new_node->prev = node->prev;
719 node->prev->next = new_node;
720 node->prev = new_node;
722 ++list->len;
726 /* ======================================================= */
727 /* Insert a new node after the specified node in the list. */
728 /* ======================================================= */
729 static void
730 ll_insert_after(ll_t * const list, ll_node_t * node, void * const data)
732 ll_node_t * new_node;
734 if (node->next == NULL)
735 ll_append(list, data);
736 else
738 new_node = ll_new_node(); /* ll_new_node cannot return NULL because it *
739 | uses xmalloc which does not return if there *
740 | is an allocation error. */
742 new_node->data = data;
743 new_node->prev = node;
744 new_node->next = node->next;
745 node->next->prev = new_node;
746 node->next = new_node;
748 ++list->len;
752 /* ================================================================= */
753 /* Remove a node from a linked list */
754 /* The memory taken by the deleted node must be freed by the caller. */
755 /* ================================================================= */
756 static int
757 ll_delete(ll_t * const list, ll_node_t * node)
759 if (list->head == list->tail)
761 if (list->head != NULL)
762 list->head = list->tail = NULL;
763 else
764 return 0;
766 else if (node->prev == NULL)
768 list->head = node->next;
769 list->head->prev = NULL;
771 else if (node->next == NULL)
773 list->tail = node->prev;
774 list->tail->next = NULL;
776 else
778 node->next->prev = node->prev;
779 node->prev->next = node->next;
782 --list->len;
784 free(node);
786 return 1;
789 #if 0 /* Unused yet */
790 /* ======================================================================== */
791 /* Find a node in the list containing data. Return the node pointer or NULL */
792 /* if not found. */
793 /* A comparison function must be provided to compare a and b (strcmp like). */
794 /* ======================================================================== */
795 static ll_node_t *
796 ll_find(ll_t * const list, void * const data,
797 int (*cmpfunc)(const void * a, const void * b))
799 ll_node_t * node;
801 if (NULL == (node = list->head))
802 return NULL;
806 if (0 == cmpfunc(node->data, data))
807 return node;
808 } while (NULL != (node = node->next));
810 return NULL;
812 #endif
814 /* ==================================================================== */
815 /* Allocate and fill an array of strings from a list. */
816 /* WARNINGS: */
817 /* 1) The list node must contain strings (char *) */
818 /* 2) The strings in the resulting array MUST NOT be freed as the are */
819 /* NOT copied from the strings of the list. */
820 /* */
821 /* IN list : The list from which the array is generated */
822 /* IN start_node : The node of the list which will be the first node to */
823 /* consider to create the array */
824 /* OUT: count : The number of elements of the resulting array. */
825 /* OUT: array : The resulting array or NULL if the list is empty. */
826 /* RC : : The number of elements of the resulting array. */
827 /* ==================================================================== */
828 static int
829 ll_strarray(ll_t * list, ll_node_t * start_node, int * count, char *** array)
831 int n = 0;
832 ll_node_t * node;
834 *count = 0;
836 node = start_node;
838 if (list == NULL || node == NULL)
840 *array = NULL;
842 return 0;
845 *array = xmalloc((list->len + 1) * sizeof(char *));
846 while (node != NULL)
848 (*array)[n++] = (char *)(node->data);
849 (*count)++;
851 node = node->next;
854 (*array)[*count] = NULL;
856 return *count;
859 /* ******************************************************************* */
860 /* BST (search.h compatible) implementation. */
861 /* */
862 /* Tree search generalized from Knuth (6.2.2) Algorithm T just like */
863 /* the AT&T man page says. */
864 /* */
865 /* Written by reading the System V Interface Definition, not the code. */
866 /* */
867 /* Totally public domain. */
868 /* ******************************************************************* */
870 struct bst_s
872 void * key;
873 struct bst_s * llink;
874 struct bst_s * rlink;
877 #if 0 /* Unused yet */
878 /* =========================== */
879 /* Delete node with given key. */
880 /* =========================== */
881 static void *
882 bst_delete(const void * vkey, void ** vrootp,
883 int (*compar)(const void *, const void *))
885 bst_t ** rootp = (bst_t **)vrootp;
886 bst_t * p, *q, *r;
887 int cmp;
889 if (rootp == NULL || (p = *rootp) == NULL)
890 return NULL;
892 while ((cmp = (*compar)(vkey, (*rootp)->key)) != 0)
894 p = *rootp;
895 rootp = (cmp < 0) ? &(*rootp)->llink /* follow llink branch */
896 : &(*rootp)->rlink; /* follow rlink branch */
897 if (*rootp == NULL)
898 return NULL; /* key not found */
900 r = (*rootp)->rlink; /* D1: */
901 if ((q = (*rootp)->llink) == NULL) /* Left NULL? */
902 q = r;
903 else if (r != NULL)
904 { /* Right link is NULL? */
905 if (r->llink == NULL)
906 { /* D2: Find successor */
907 r->llink = q;
908 q = r;
910 else
911 { /* D3: Find NULL link */
912 for (q = r->llink; q->llink != NULL; q = r->llink)
913 r = q;
914 r->llink = q->rlink;
915 q->llink = (*rootp)->llink;
916 q->rlink = (*rootp)->rlink;
919 if (p != *rootp)
920 free(*rootp); /* D4: Free node */
921 *rootp = q; /* link parent to new node */
922 return p;
924 #endif
926 /* ===================================================================== */
927 /* Destroy a tree. */
928 /* The clean function pointer can be NULL, in this case the node content */
929 /* is not freed. */
930 /* ===================================================================== */
931 static void
932 bst_destroy(void * vrootp, void (*clean)(void *))
934 bst_t * root = (bst_t *)vrootp;
936 if (root == NULL)
937 return;
939 bst_destroy(root->llink, clean);
940 bst_destroy(root->rlink, clean);
942 if (clean)
943 clean((void *)root->key);
945 free(root);
948 /* ========================= */
949 /* Find a node, or return 0. */
950 /* ========================= */
951 static void *
952 bst_find(const void * vkey, void * const * vrootp,
953 int (*compar)(const void *, const void *))
955 bst_t * const * rootp = (bst_t * const *)vrootp;
957 if (rootp == NULL)
958 return NULL;
960 while (*rootp != NULL)
961 { /* T1: */
962 int r;
964 if ((r = (*compar)(vkey, (*rootp)->key)) == 0) /* T2: */
965 return *rootp; /* key found */
966 rootp = (r < 0) ? &(*rootp)->llink /* T3: follow left branch */
967 : &(*rootp)->rlink; /* T4: follow right branch */
969 return NULL;
972 /* ======================================= */
973 /* Find or inserts datum into search tree. */
974 /* ======================================= */
975 static void *
976 bst_search(void * vkey, void ** vrootp,
977 int (*compar)(const void *, const void *))
979 bst_t * q;
980 bst_t ** rootp = (bst_t **)vrootp;
982 if (rootp == NULL)
983 return NULL;
985 while (*rootp != NULL)
986 { /* Knuth's T1: */
987 int r;
989 if ((r = (*compar)(vkey, (*rootp)->key)) == 0) /* T2: */
990 return *rootp; /* we found it! */
992 rootp = (r < 0) ? &(*rootp)->llink /* T3: follow left branch */
993 : &(*rootp)->rlink; /* T4: follow right branch */
996 q = xmalloc(sizeof(bst_t)); /* T5: key not found */
997 if (q != 0)
998 { /* make new node */
999 *rootp = q; /* link new node to old */
1000 q->key = vkey; /* initialize new node */
1001 q->llink = q->rlink = NULL;
1003 return q;
1006 /* ========================= */
1007 /* Walk the nodes of a tree. */
1008 /* ========================= */
1009 static void
1010 bst_walk_recurse(const bst_t * root,
1011 void (*action)(const void *, walk_order_e, int), int level)
1013 if (root->llink == NULL && root->rlink == NULL)
1014 (*action)(root, leaf, level);
1015 else
1017 (*action)(root, preorder, level);
1018 if (root->llink != NULL)
1019 bst_walk_recurse(root->llink, action, level + 1);
1020 (*action)(root, postorder, level);
1021 if (root->rlink != NULL)
1022 bst_walk_recurse(root->rlink, action, level + 1);
1023 (*action)(root, endorder, level);
1027 static void
1028 bst_walk(const void * vroot, void (*action)(const void *, walk_order_e, int))
1030 if (vroot != NULL && action != NULL)
1031 bst_walk_recurse(vroot, action, 0);
1034 /* ************************ */
1035 /* Various implementations. */
1036 /* ************************ */
1038 /* ======================== */
1039 /* Trim leading characters. */
1040 /* ======================== */
1041 static void
1042 ltrim(char * str, const char * trim_str)
1044 size_t len = strlen(str);
1045 size_t begin = strspn(str, trim_str);
1046 size_t i;
1048 if (begin > 0)
1049 for (i = begin; i <= len; ++i)
1050 str[i - begin] = str[i];
1053 /* ================================================= */
1054 /* Trim trailing characters. */
1055 /* The resulting string will have at least min bytes */
1056 /* even if trailing spaces remain. */
1057 /* ================================================= */
1058 static void
1059 rtrim(char * str, const char * trim_str, size_t min)
1061 size_t len = strlen(str);
1062 while (len > min && strchr(trim_str, str[len - 1]))
1063 str[--len] = '\0';
1066 /* ================================================== */
1067 /* Count the number of occurrences of the character c */
1068 /* in the string str. */
1069 /* The str pointer is assumed to be not NULL. */
1070 /* ================================================== */
1071 static int
1072 strchrcount(char * str, char c)
1074 int count = 0;
1076 while (*str)
1077 if (*str++ == c)
1078 count++;
1080 return count;
1083 /* =============================================== */
1084 /* Is the string str2 a prefix of the string str1? */
1085 /* =============================================== */
1086 static int
1087 strpref(char * str1, char * str2)
1089 while (*str1 != '\0' && *str1 == *str2)
1091 str1++;
1092 str2++;
1095 return *str2 == '\0';
1098 /* ========================== */
1099 /* Like strcmp ignoring case. */
1100 /* ========================== */
1101 static int
1102 stricmp(const char * s1, const char * s2)
1104 while (tolower((unsigned char)*s1) == tolower((unsigned char)*s2))
1106 if (*s1 == '\0')
1107 return 0;
1109 s1++;
1110 s2++;
1113 return (int)tolower((unsigned char)*s1) - (int)tolower((unsigned char)*s2);
1116 /* ======================================================================== */
1117 /* Strings concatenation with dynamic memory allocation. */
1118 /* IN : a variable number of char * arguments with NULL terminating */
1119 /* the sequence. */
1120 /* The first one must have been dynamically allocated and is mandatory */
1121 /* */
1122 /* Returns a new allocated string containing the concatenation of all */
1123 /* the arguments. It is the caller's responsibility to free the resulting */
1124 /* string. */
1125 /* ======================================================================== */
1126 static char *
1127 strappend(char * str, ...)
1129 size_t l;
1130 va_list args;
1131 char * s;
1133 l = 1 + strlen(str);
1134 va_start(args, str);
1136 s = va_arg(args, char *);
1138 while (s)
1140 l += strlen(s);
1141 s = va_arg(args, char *);
1144 va_end(args);
1146 str = xrealloc(str, l);
1148 va_start(args, str);
1149 s = va_arg(args, char *);
1151 while (s)
1153 strcat(str, s);
1154 s = va_arg(args, char *);
1156 va_end(args);
1158 return str;
1161 /* ====================================================================== */
1162 /* Public domain strtok_r() by Charlie Gordon. */
1163 /* from comp.lang.c 9/14/2007 */
1164 /* http://groups.google.com/group/comp.lang.c/msg/2ab1ecbb86646684 */
1165 /* */
1166 /* (Declaration that it's public domain): */
1167 /* http://groups.google.com/group/comp.lang.c/msg/7c7b39328fefab9c */
1168 /* */
1169 /* Also, fixed by Fletcher T. Penney --- added the "return NULL" when */
1170 /* *end == NULL */
1171 /* ====================================================================== */
1172 static char *
1173 xstrtok_r(char * str, const char * delim, char ** end)
1175 char * ret;
1177 if (str == NULL)
1178 str = *end;
1180 if (str == NULL)
1181 return NULL;
1183 str += strspn(str, delim);
1185 if (*str == '\0')
1186 return NULL;
1188 ret = str;
1190 str += strcspn(str, delim);
1192 if (*str)
1193 *str++ = '\0';
1195 *end = str;
1197 return ret;
1200 /* ===================================================================== */
1201 /* Put the first word of str, truncated to len characters, in buf. */
1202 /* Return a pointer in str pointing just after the word. */
1203 /* buf must have been pre-allocated to accept at least len+1 characters. */
1204 /* Note that buf can contains a sting full of spaces is str was not */
1205 /* trimmed before the call. */
1206 /* ===================================================================== */
1207 char *
1208 get_word(char * str, char * buf, size_t len)
1210 char * s = str;
1212 /* Skip spaces. */
1213 /* """""""""""" */
1214 while (*s && isspace(*s))
1215 s++;
1217 /* Set the new string start. */
1218 /* """"""""""""""""""""""""" */
1219 str = s;
1221 /* Get the word. */
1222 /*"""""""""""""" */
1223 while (*s && !isspace(*s) && s - str < len)
1224 s++;
1226 strncpy(buf, str, s - str);
1227 buf[s - str] = 0;
1229 return s;
1232 /* ==================================================================== */
1233 /* Return 1 is value is "1" or "yes" (ignoring case). */
1234 /* Return 0 is value is "0" or "no" (ignoring case). */
1235 /* If value has another value, then set invalid to 1 and also return 0 */
1236 /* invalid is set to 0i in all the other cases. */
1237 /* ==================================================================== */
1238 static int
1239 eval_yes(char * value, int * invalid)
1241 *invalid = 0;
1243 if (strcmp(value, "1") == 0 || stricmp(value, "yes") == 0)
1244 return 1;
1245 else if (strcmp(value, "0") != 0 && stricmp(value, "no") != 0)
1246 *invalid = 1;
1248 return 0;
1251 /* =========================================================== */
1252 /* Fill an array of strings from the words composing a string. */
1253 /* */
1254 /* str: initial string which will be altered. */
1255 /* args: array of pointers to the start of the words in str. */
1256 /* max: maximum number of words used before giving up. */
1257 /* return: the number of words (<=max). */
1258 /* =========================================================== */
1259 static int
1260 str2argv(char * str, char ** args, int max)
1262 int nb_args = 0;
1264 while (*str)
1266 if (nb_args >= max)
1267 return nb_args;
1269 while (*str == ' ' || *str == '\t')
1270 *(str++) = '\0';
1272 if (!*str)
1273 return nb_args;
1275 args[nb_args] = str;
1276 nb_args++;
1278 while (*str && (*str != ' ') && (*str != '\t'))
1279 str++;
1282 return nb_args;
1285 /* ********************** */
1286 /* ctxopt implementation. */
1287 /* ********************** */
1289 static int ctxopt_initialized = 0; /* cap_init has not yet been called */
1291 /* Flags structure initialized by ctxopt_init. */
1292 /* """"""""""""""""""""""""""""""""""""""""""" */
1293 struct flags_s
1295 int stop_if_non_option;
1296 int allow_abbreviations;
1299 /* Context structure. */
1300 /* """""""""""""""""" */
1301 struct ctx_s
1303 char * name;
1304 ll_t * opt_list; /* list of options allowed in this context. */
1305 ll_t * incomp_list; /* list of strings containing incompatible names *
1306 | of options separated by spaces or tabs. */
1307 int (*action)(char * name, int type, char * new_ctx, int ctx_nb_data,
1308 void ** ctx_data);
1309 void * par_bst;
1310 int nb_data;
1311 void ** data;
1314 /* https://textik.com/#488ce3649b6c60f5 */
1315 /* */
1316 /* +--------------+ */
1317 /* |first_ctx_inst| */
1318 /* +---+----------+ */
1319 /* | */
1320 /* +--v-----+ +--------+ +--------+ +-----+ */
1321 /* +---+-->ctx_inst+------>opt_inst+----->opt_inst+------> ... | */
1322 /* | | +-+------+ +----+---+ +----+---+ +-----+ */
1323 /* | | | | | */
1324 /* | | +-v------+ | | */
1325 /* | +--+ctx_inst<-----------+ | */
1326 /* | +-+------+ | */
1327 /* | | | */
1328 /* | +-v------+ | */
1329 /* +------+ctx_inst<--------------------------+ */
1330 /* +-+------+ */
1331 /* | */
1332 /* +-v---+ */
1333 /* | ... | */
1334 /* +-----+ */
1336 /* Option structure. */
1337 /* """"""""""""""""" */
1338 struct opt_s
1340 char * name; /* option name. */
1341 char * next_ctx; /* new context this option may lead to */
1342 ll_t * ctx_list; /* list of contexts allowing this option. */
1343 char * params; /* string containing all the parameters of *
1344 | the option. */
1346 void (*action)( /* The option associated action. */
1347 char * ctx_name, /* context name. */
1348 char * opt_name, /* option name. */
1349 char * par, /* option parameter. */
1350 int nb_args, /* number of arguments. */
1351 char ** args, /* option arguments. */
1352 int nb_opt_data, /* number of option data pointers. */
1353 void ** opt_data, /* option data pointers. */
1354 int nb_ctx_data, /* nb of current context data ptrs. */
1355 void ** ctx_data /* current context data pointers. */
1358 int nb_data; /* number of the data pointers passed as argument to action. */
1359 void ** data; /* array of data pointers passed as argument to action. */
1361 int args; /* 1 if this option takes arguments else 0. */
1362 int optional; /* 1 if the option is optional, else 0. */
1363 int multiple; /* 1 if the option can appear more than one time in a *
1364 | context, else 0. */
1366 int opt_count_matter; /* 1 if we must restrict the count, else 0. */
1367 int occurrences; /* Number of option occurrences in a context. */
1368 char opt_count_oper; /* <, = or > */
1369 unsigned opt_count_mark; /* Value to be compared to with opt_count_oper. */
1371 char * arg; /* symbolic text after # describing the option argument. */
1373 int optional_args; /* 1 of option is optional else 0. */
1374 int multiple_args; /* 1 is option can appear more than once in a context *
1375 | instance. */
1377 int opt_args_count_matter; /* 1 if count is rescticted, else 0. */
1378 char opt_args_count_oper; /* <, = or > */
1379 unsigned opt_args_count_mark; /* Value to be compared to with *
1380 | opt_count_oper. */
1382 int eval_first; /* 1 if this option must be evaluated before the options *
1383 | without this mark. */
1385 ll_t * constraints_list; /* List of constraint check functions pointers. */
1388 /* Context instance structure. */
1389 /* """"""""""""""""""""""""""" */
1390 struct ctx_inst_s
1392 ctx_t * ctx; /* the context whose this is an instance of */
1393 ctx_inst_t * prev_ctx_inst; /* ctx_inst of the opt_inst which led to the *
1394 | creation of this ctx_inst structure. */
1395 opt_inst_t * gen_opt_inst; /* opt_inst which led to the creation of a *
1396 | instance of this structure. */
1397 ll_t * incomp_bst_list; /* list of seen_opt_t BST. */
1398 void * seen_opt_bst; /* tree of seen_opt_t. */
1399 ll_t * opt_inst_list; /* The list of option instances in this *
1400 | context instance. */
1401 char * par_name; /* parameter which created this instance. */
1404 /* Option instance structure. */
1405 /* """""""""""""""""""""""""" */
1406 struct opt_inst_s
1408 opt_t * opt; /* The option this is an instance of. */
1409 char * opt_name; /* The option which led to this creation. */
1410 char * par; /* The parameter which led to this creation. */
1411 ll_t * values_list; /* The list of arguments of this option. */
1412 ctx_inst_t * next_ctx_inst; /* The new context instance this option. *
1413 | instance may create. */
1416 /* Structure used to check if an option has bee seen or not */
1417 /* in a context instance. */
1418 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""" */
1419 struct seen_opt_s
1421 opt_t * opt; /* The concerned option. */
1422 char * par; /* Parameter which led to the making of this structure. */
1423 int seen; /* 1 if seen in the context instances, else 0. */
1426 /* Parameter structure which links a parameter to the option it belongs to. */
1427 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
1428 struct par_s
1430 char * name; /* Parameter name (with the leading -). */
1431 opt_t * opt; /* Attached option. */
1434 /* Constraint structure. */
1435 /* """"""""""""""""""""" */
1436 struct constraint_s
1438 int (*constraint)(int nb_args, char ** args, char * value, char * parameter);
1439 int nb_args;
1440 char ** args;
1441 char * to_free; /* pointer to the original string in which the array in *
1442 | args points to. This poinnter is kept there to allow *
1443 | it to be freed. */
1446 state_t * cur_state = NULL; /* Current analysis state. */
1447 static ll_t * cmdline_list; /* List of interpreted CLI words *
1448 | serves as the basis for the *
1449 | analysis of the parameters. */
1450 static ctx_t * main_ctx = NULL; /* initial context. */
1451 static ctx_inst_t * first_ctx_inst = NULL; /* Pointer to the fist context *
1452 | instance which holds the *
1453 | options instances. */
1454 static ll_t * ctx_inst_list = NULL; /* List of the context instances. */
1456 static flags_t flags = { 0, 1 };
1458 /* ======================================================= */
1459 /* Parse a string for the next matching token. */
1460 /* */
1461 /* s: string to parse. */
1462 /* token: pre_allocated array of max tok_len characters. */
1463 /* pattern: scanf type pattern token must match. */
1464 /* pos: number of characters successfully parsed in s. */
1465 /* */
1466 /* Returns: a pointer to the first unread character or */
1467 /* to he terminating \0. */
1468 /* ======================================================= */
1469 static char *
1470 strtoken(char * s, char * token, size_t tok_len, char * pattern, int * pos)
1472 char * full_pattern;
1473 char len[3];
1474 int n;
1476 *pos = 0;
1478 n = snprintf(len, 3, "%zu", tok_len);
1479 if (n < 0)
1480 return NULL;
1482 full_pattern = xmalloc(strlen(pattern) + n + 4);
1484 strcpy(full_pattern, "%");
1485 strcat(full_pattern, len);
1486 strcat(full_pattern, pattern);
1487 strcat(full_pattern, "%n");
1489 n = sscanf(s, full_pattern, token, pos);
1491 free(full_pattern);
1493 if (n != 1)
1494 return NULL;
1496 return s + *pos;
1499 /* ****************************************** */
1500 /* Various comparison and deletion functions. */
1501 /* ****************************************** */
1503 static int
1504 ctx_compare(const void * c1, const void * c2)
1506 return strcmp(((ctx_t *)c1)->name, ((ctx_t *)c2)->name);
1509 /* =========================== */
1510 /* Free a context_bst element. */
1511 /* =========================== */
1512 static void
1513 ctx_free(void * c)
1515 ctx_t * ctx = c;
1517 free(ctx->name);
1518 free(ctx->data);
1520 ll_destroy(ctx->opt_list, NULL);
1521 ll_destroy(ctx->incomp_list, free);
1522 bst_destroy(ctx->par_bst, par_free);
1524 free(c);
1527 /* ============================= */
1528 /* Free a ctx_inst_list element. */
1529 /* ============================= */
1530 static void
1531 ctx_inst_free(void * ci)
1533 ctx_inst_t * ctx_inst = ci;
1535 free(ctx_inst->par_name);
1536 ll_destroy(ctx_inst->incomp_bst_list, incomp_bst_free);
1537 bst_destroy(ctx_inst->seen_opt_bst, seen_opt_free);
1538 ll_destroy(ctx_inst->opt_inst_list, opt_inst_free);
1540 free(ci);
1543 /* ============================= */
1544 /* Free a opt_inst_list element. */
1545 /* ============================= */
1546 static void
1547 opt_inst_free(void * oi)
1549 opt_inst_t * opt_inst = oi;
1551 ll_destroy(opt_inst->values_list, NULL);
1553 free(oi);
1556 /* ================================== */
1557 /* Compare two seen_opt_bst elements. */
1558 /* ================================== */
1559 static int
1560 seen_opt_compare(const void * so1, const void * so2)
1562 opt_t *o1, *o2;
1564 o1 = ((seen_opt_t *)so1)->opt;
1565 o2 = ((seen_opt_t *)so2)->opt;
1567 return strcmp(o1->name, o2->name);
1570 /* ============================ */
1571 /* Free a seen_opt_bst element. */
1572 /* ============================ */
1573 void
1574 seen_opt_free(void * so)
1576 seen_opt_t * seen_opt = so;
1578 free(seen_opt->par);
1580 free(so);
1583 /* =========================== */
1584 /* Free an incomp_bst element. */
1585 /* =========================== */
1586 static void
1587 incomp_bst_free(void * b)
1589 bst_t * bst = b;
1591 bst_destroy(bst, NULL);
1594 /* ================================= */
1595 /* Compare two options_bst elements. */
1596 /* ================================= */
1597 static int
1598 opt_compare(const void * o1, const void * o2)
1600 return strcmp(((opt_t *)o1)->name, ((opt_t *)o2)->name);
1603 /* ============================= */
1604 /* Free an options_bst elements. */
1605 /* ============================= */
1606 void
1607 opt_free(void * o)
1609 opt_t * opt = o;
1611 free(opt->name);
1612 free(opt->next_ctx);
1613 free(opt->params);
1614 free(opt->arg);
1615 free(opt->data);
1617 ll_destroy(opt->ctx_list, NULL);
1618 ll_destroy(opt->constraints_list, constraint_free);
1620 free(o);
1623 /* ============================= */
1624 /* Compare two par_bst elements. */
1625 /* ============================= */
1626 static int
1627 par_compare(const void * a1, const void * a2)
1629 return strcmp(((par_t *)a1)->name, ((par_t *)a2)->name);
1632 /* ======================= */
1633 /* Free a par_bst element. */
1634 /* ======================= */
1635 static void
1636 par_free(void * p)
1638 par_t * par = p;
1640 free(par->name);
1642 free(p);
1645 /* ================================ */
1646 /* Free a constraints_list element. */
1647 /* ================================ */
1648 static void
1649 constraint_free(void * c)
1651 constraint_t * cstr = c;
1653 free(cstr->args);
1654 free(cstr->to_free);
1656 free(c);
1659 /* ******************************************************************** */
1660 /* Helper functions to locate contexts, options and parameters in a BST */
1661 /* by their names. */
1662 /* ******************************************************************** */
1664 static ctx_t *
1665 locate_ctx(char * name)
1667 bst_t * node;
1668 ctx_t ctx = { 0 };
1670 ctx.name = name;
1672 if ((node = bst_find(&ctx, &contexts_bst, ctx_compare)) == NULL)
1673 return NULL;
1674 else
1675 return node->key;
1678 static opt_t *
1679 locate_opt(char * name)
1681 bst_t * node;
1682 opt_t opt = { 0 };
1684 opt.name = name;
1686 if ((node = bst_find(&opt, &options_bst, opt_compare)) == NULL)
1687 return NULL;
1688 else
1689 return node->key;
1692 static par_t *
1693 locate_par(char * name, ctx_t * ctx)
1695 bst_t * node;
1696 par_t par = { 0 };
1697 void * bst = ctx->par_bst;
1699 par.name = name;
1701 if ((node = bst_find(&par, &bst, par_compare)) == NULL)
1702 return NULL;
1703 else
1704 return node->key;
1707 /* =================================================================== */
1708 /* Utility function to format and print the options present in a list. */
1709 /* */
1710 /* IN list : a list of options. */
1711 /* OUT has_* : a set of flags which will determine the content of the */
1712 /* explanation given after the formatted printing of the */
1713 /* options. */
1714 /* =================================================================== */
1715 static void
1716 print_options(ll_t * list, int * has_optional, int * has_ellipsis,
1717 int * has_rule, int * has_generic_arg, int * has_ctx_change,
1718 int * has_early_eval)
1720 ll_node_t * node = list->head;
1721 opt_t * opt;
1722 char * line;
1723 char * option;
1725 line = xstrdup(" ");
1727 while (node != NULL)
1729 option = xstrdup("");
1730 opt = node->data;
1732 if (opt->optional)
1734 option = strappend(option, "[", NULL);
1735 *has_optional = 1;
1738 if (opt->eval_first)
1740 option = strappend(option, "*", NULL);
1741 *has_early_eval = 1;
1744 option = strappend(option, opt->params, NULL);
1746 if (opt->next_ctx != NULL)
1748 option = strappend(option, ">", opt->next_ctx, NULL);
1749 *has_ctx_change = 1;
1752 if (opt->multiple)
1754 if (opt->opt_count_oper != '\0')
1756 char m[4];
1757 char o[2];
1758 o[0] = opt->opt_count_oper;
1759 o[1] = '\0';
1760 snprintf(m, 3, "%u", opt->opt_count_mark);
1761 option = strappend(option, "...", o, m, NULL);
1762 *has_rule = 1;
1764 else
1765 option = strappend(option, "...", NULL);
1767 *has_ellipsis = 1;
1770 if (opt->args)
1772 if (*(opt->arg) == '#')
1773 *has_generic_arg = 1;
1775 option = strappend(option, " ", NULL);
1777 if (opt->optional_args)
1779 option = strappend(option, "[", opt->arg, NULL);
1780 *has_optional = 1;
1782 else
1783 option = strappend(option, opt->arg, NULL);
1785 if (opt->multiple_args)
1787 if (opt->opt_args_count_oper != '\0')
1789 char m[4];
1790 char o[2];
1791 o[0] = opt->opt_args_count_oper;
1792 o[1] = '\0';
1793 snprintf(m, 3, "%u", opt->opt_args_count_mark);
1794 option = strappend(option, "...", o, m, NULL);
1795 *has_rule = 1;
1797 else
1798 option = strappend(option, "...", NULL);
1800 *has_ellipsis = 1;
1802 if (opt->optional_args)
1803 option = strappend(option, "]", NULL);
1805 if (opt->optional)
1806 option = strappend(option, "]", NULL);
1808 if (strlen(line) + 1 + strlen(option) < 80)
1809 line = strappend(line, option, " ", NULL);
1810 else
1812 printf("%s\n", line);
1813 line[2] = '\0';
1814 line = strappend(line, option, " ", NULL);
1817 free(option);
1819 node = node->next;
1822 printf("%s\n", line);
1824 free(line);
1827 /* ==================================================== */
1828 /* Explain the special syntactic symbols present in the */
1829 /* generated usage messages. */
1830 /* ==================================================== */
1831 static void
1832 print_explanations(int has_early_eval, int has_ctx_change, int has_generic_arg,
1833 int has_optional, int has_ellipsis, int has_rule)
1835 if (has_early_eval || has_ctx_change || has_generic_arg || has_optional
1836 || has_ellipsis || has_rule)
1838 printf("\nExplanation of the syntax used above:\n");
1839 printf("Only the parameters (prefixed by -) and the arguments, if any, "
1840 "must be entered.\n");
1841 printf("The following is just there to explain the other symbols "
1842 "displayed.\n\n");
1844 if (has_early_eval)
1845 printf("* : the parameters for this option will be "
1846 "evaluated first.\n");
1847 if (has_ctx_change)
1848 printf(
1849 "> : The context after this symbol will become the next "
1850 "default one.\n");
1851 if (has_generic_arg)
1852 printf("#tag : argument tag giving a clue to its meaning.\n");
1853 if (has_optional)
1854 printf(
1855 "[...] : the object between square brackets is optional.\n");
1856 if (has_ellipsis)
1857 printf("... : several occurrences of the previous object "
1858 "are possible.\n");
1859 if (has_rule)
1860 printf("[<|=|>]number: rules constraining the number of "
1861 "parameters/arguments.\n");
1865 /* ************************************************************ */
1866 /* Various utilities and callback functions called when walking */
1867 /* through a BST. */
1868 /* ************************************************************ */
1870 static void
1871 bst_seen_opt_cb(const void * node, walk_order_e kind, int level)
1873 seen_opt_t * seen_opt = ((bst_t *)node)->key;
1875 if (kind == postorder || kind == leaf)
1877 if ((!seen_opt->opt->optional) && seen_opt->seen == 0)
1879 user_rc = 1;
1880 user_string = strappend(user_string, seen_opt->opt->params, " ", NULL);
1885 static void
1886 bst_seen_opt_seen_cb(const void * node, walk_order_e kind, int level)
1888 seen_opt_t * seen_opt = ((bst_t *)node)->key;
1890 if (kind == postorder || kind == leaf)
1891 if (seen_opt->seen == 1)
1893 user_rc = 1;
1894 user_object = seen_opt->par;
1898 static void
1899 bst_print_ctx_cb(const void * node, walk_order_e kind, int level)
1901 ctx_t * ctx = main_ctx;
1902 ctx_t * cur_ctx = ((bst_t *)node)->key;
1904 ll_t * list;
1906 int has_optional = 0;
1907 int has_ellipsis = 0;
1908 int has_rule = 0;
1909 int has_generic_arg = 0;
1910 int has_ctx_change = 0;
1911 int has_early_eval = 0;
1913 if (kind == postorder || kind == leaf)
1914 if (strcmp(ctx->name, cur_ctx->name) != 0)
1916 list = cur_ctx->opt_list;
1918 printf("\nAllowed options in the context %s:\n", cur_ctx->name);
1919 print_options(list, &has_optional, &has_ellipsis, &has_rule,
1920 &has_generic_arg, &has_ctx_change, &has_early_eval);
1924 static void
1925 bst_check_opt_cb(const void * node, walk_order_e kind, int level)
1927 opt_t * opt = ((bst_t *)node)->key;
1929 if (kind == postorder || kind == leaf)
1931 if (opt->params == NULL) /* opt must have associated parameters. */
1932 fatal_internal("Option %s has no registered parameter.\n", opt->name);
1934 if (opt->action == NULL) /* opt must have an action. */
1935 fatal_internal("Option %s has no registered action.\n", opt->name);
1939 static void
1940 bst_match_par_cb(const void * node, walk_order_e kind, int level)
1942 ctx_t * ctx = ((bst_t *)node)->key;
1944 if (kind == postorder || kind == leaf)
1946 char * str = xstrdup(user_string);
1948 while (*str != '\0')
1950 if (locate_par(str, ctx) != NULL)
1952 user_string2 = strappend(user_string2, " ", ctx->name, NULL);
1953 break;
1955 str[strlen(str) - 1] = '\0';
1957 free(str);
1961 static void
1962 match_prefix_cb(const void * node, walk_order_e kind, int level)
1964 par_t * par = ((bst_t *)node)->key;
1966 if (kind == postorder || kind == leaf)
1967 if (strpref(par->name, (char *)user_object))
1969 user_rc++;
1970 user_string = strappend(user_string, par->name, " ", NULL);
1974 /* ====================================================================== */
1975 /* A parameter may not be separated from its first option by spaces, in */
1976 /* this case this function looks for a valid flag as a prefix and splits */
1977 /* the command line queue (eg: "-pa1" -> "-pa" "1" if "-pa" is a valid */
1978 /* option). */
1979 /* */
1980 /* IN word : the word to be checked. */
1981 /* IN ctx : the context in which the flag indexed by the word is to be */
1982 /* checked. */
1983 /* OUT pos : the offset in word pointing just after the matching prefix. */
1984 /* OUT opt : a pointer to the option associated with the new parameter */
1985 /* or NULL if none is found. */
1986 /* */
1987 /* The returned pointer must be freed by the caller. */
1988 /* ====================================================================== */
1989 static char *
1990 look_for_valid_prefix_in_word(char * word, ctx_t * ctx, int * pos, opt_t ** opt)
1992 char * new = NULL;
1993 int len;
1994 par_t * par;
1995 par_t tmp_par = { 0 };
1997 len = strlen(word);
1999 if (len > 2)
2001 new = xstrdup(word);
2005 new[--len] = '\0';
2006 tmp_par.name = new;
2007 } while ((par = locate_par(tmp_par.name, ctx)) == NULL && len > 2);
2009 if (par != NULL)
2011 *pos = len;
2012 *opt = par->opt;
2014 else
2016 free(new);
2017 new = NULL;
2020 else
2021 *pos = 0;
2023 return new;
2026 /* ============================================================= */
2027 /* If par_name is an unique abbreviation of an exiting parameter */
2028 /* in the context ctx, then return this parameter. */
2029 /* ============================================================= */
2030 static char *
2031 abbrev_expand(char * par_name, ctx_t * ctx)
2033 user_object = par_name;
2034 user_rc = 0;
2036 *user_string = '\0';
2037 bst_walk(ctx->par_bst, match_prefix_cb);
2038 rtrim(user_string, " ", 0);
2040 /* The previous bst_walk has built a string of blank separated parameters */
2041 /* all having par_name as prefix. This string is put in the user_string */
2042 /* exchange zone. The number of these words in put in user_rc. */
2043 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2044 if (user_rc == 1) /* The number of matching abbreviations. */
2045 return xstrdup(user_string);
2046 else /* There is at least tho defined parameters starting with par_name. */
2048 char * s, *first_s;
2049 par_t * par;
2050 opt_t * opt;
2051 int opt_count = 0;
2052 void * tmp_opt_bst = NULL;
2054 /* Find all the options corresponding to these words and store them */
2055 /* without duplication in a temporary BST. Only their resulting count */
2056 /* matters. */
2057 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2058 s = first_s = strtok(user_string, " "); /* first_s holds a copy of *
2059 | the first word. */
2060 while (s != NULL)
2062 par = locate_par(s, ctx);
2063 opt = par->opt;
2065 if (bst_find(opt, &tmp_opt_bst, opt_compare) == NULL)
2067 /* This option as not already been seen */
2068 /* store it and increase the seen counter. */
2069 /* """"""""""""""""""""""""""""""""""""""" */
2070 bst_search(opt, &tmp_opt_bst, opt_compare);
2071 opt_count++;
2073 s = strtok(NULL, " ");
2076 /* Clean the temporary BST without removing the pointer */
2077 /* to the real options. */
2078 /* """""""""""""""""""""""""""""""""""""""""""""""""""" */
2079 if (tmp_opt_bst != NULL)
2080 bst_destroy(tmp_opt_bst, NULL);
2082 if (opt_count == 1)
2083 /* All the abbreviation are leading to only one option */
2084 /* We can just continue as in the previous case. */
2085 /* """"""""""""""""""""""""""""""""""""""""""""""""""" */
2086 return xstrdup(first_s);
2087 else
2088 return NULL;
2092 /* ================================================================ */
2093 /* Terminate the program if mandatory options required by a context */
2094 /* are not present. */
2095 /* ================================================================ */
2096 static void
2097 check_for_missing_mandatory_opt(ctx_inst_t * ctx_inst, char * opt_par)
2099 char * missing;
2101 if (has_unseen_mandatory_opt(ctx_inst, &missing))
2102 fatal(CTXOPTMISPAR, missing);
2105 /* ====================================================== */
2106 /* Return 1 if at least one mandatory option was not seen */
2107 /* when quitting a context, else 0. */
2108 /* ====================================================== */
2109 static int
2110 has_unseen_mandatory_opt(ctx_inst_t * ctx_inst, char ** missing)
2112 user_rc = 0;
2113 *user_string = '\0';
2115 bst_walk(ctx_inst->seen_opt_bst, bst_seen_opt_cb);
2116 rtrim(user_string, " ", 0);
2118 *missing = user_string;
2120 return user_rc ? 1 : 0;
2123 /* ========================================================================= */
2124 /* This function terminates the program if an option or its arguments do not */
2125 /* conform to its occurrences constraint. */
2126 /* There constraints can appear by trailing >, < or = in their definition */
2127 /* given in ctxopt_new_ctx. */
2128 /* ========================================================================= */
2129 static void
2130 check_for_occurrences_issues(ctx_inst_t * ctx_inst)
2132 ctx_t * ctx = ctx_inst->ctx;
2133 opt_t * opt;
2134 ll_node_t * node;
2135 opt_inst_t * opt_inst;
2136 char * cur_opt_params = cur_state->cur_opt_params;
2137 char * cur_opt_par_name = cur_state->cur_opt_par_name;
2139 /* Checks options. */
2140 /* """"""""""""""" */
2141 node = ctx->opt_list->head;
2143 while (node != NULL)
2145 opt = node->data;
2147 /* Update current_state. */
2148 /* """"""""""""""""""""" */
2149 cur_state->cur_opt_params = opt->params;
2150 cur_state->opts_count = opt->opt_count_mark;
2151 cur_state->opt_args_count = opt->opt_args_count_mark;
2153 if (opt->opt_count_matter)
2154 switch (opt->opt_count_oper)
2156 case '=':
2157 if (opt->occurrences > 0 && opt->opt_count_mark != opt->occurrences)
2158 fatal(CTXOPTCTEOPT, NULL);
2159 break;
2161 case '<':
2162 if (opt->occurrences > 0 && opt->opt_count_mark <= opt->occurrences)
2163 fatal(CTXOPTCTLOPT, NULL);
2164 break;
2166 case '>':
2167 if (opt->occurrences > 0 && opt->opt_count_mark >= opt->occurrences)
2168 fatal(CTXOPTCTGOPT, NULL);
2169 break;
2172 node = node->next;
2175 /* Checks arguments. */
2176 /* """"""""""""""""" */
2177 node = ctx_inst->opt_inst_list->head;
2178 while (node != NULL)
2180 opt_inst = node->data;
2181 opt = opt_inst->opt;
2183 /* Update current_state. */
2184 /* """"""""""""""""""""" */
2185 cur_state->cur_opt_par_name = opt_inst->par;
2186 cur_state->opts_count = opt->opt_count_mark;
2187 cur_state->opt_args_count = opt->opt_args_count_mark;
2189 int nb_values = opt_inst->values_list->len; /* Number of arguments of opt */
2191 if (opt->opt_args_count_matter)
2192 switch (opt->opt_args_count_oper)
2194 case '=':
2195 if (nb_values > 0 && opt->opt_args_count_mark != nb_values)
2196 fatal(CTXOPTCTEARG, NULL);
2197 break;
2199 case '<':
2200 if (nb_values > 0 && opt->opt_args_count_mark <= nb_values)
2201 fatal(CTXOPTCTLARG, NULL);
2202 break;
2204 case '>':
2205 if (nb_values > 0 && opt->opt_args_count_mark >= nb_values)
2206 fatal(CTXOPTCTGARG, NULL);
2207 break;
2210 node = node->next;
2212 cur_state->cur_opt_params = cur_opt_params;
2213 cur_state->cur_opt_par_name = cur_opt_par_name;
2216 /* ======================================================================== */
2217 /* Parse a strings describing options and some of their characteristics */
2218 /* The input string must have follow some rules like in the examples below: */
2219 /* */
2220 /* "opt_name1 opt_name2" */
2221 /* "[opt_name1] opt_name2" */
2222 /* "[opt_name1] opt_name2..." */
2223 /* "[opt_name1 #...] opt_name2... [#]" */
2224 /* "[opt_name1 [#...]] opt_name2... [#...]" */
2225 /* */
2226 /* Where [ ] encloses an optional part, # means: has parameters and ... */
2227 /* means that there can be more than one occurrence of the previous thing. */
2228 /* */
2229 /* opt_name can be followed by a 'new context' change prefixed with the */
2230 /* symbol >, as in opt1>c2 by eg. */
2231 /* */
2232 /* This function returns as soon as one (or no) option has been parsed and */
2233 /* return the offset to the next option to parse. */
2234 /* */
2235 /* In case of successful parsing, an new option is allocated and its */
2236 /* pointer returned. */
2237 /* ======================================================================== */
2238 static int
2239 opt_parse(char * s, opt_t ** opt)
2241 int opt_optional = 0;
2242 int opt_multiple = 0;
2243 int opt_count_matter = 0;
2244 char opt_count_oper = '\0';
2245 unsigned opt_count_mark = 0;
2246 int opt_args = 0;
2247 char opt_arg[33] = { 0 };
2248 int opt_multiple_args = 0;
2249 int opt_args_count_matter = 0;
2250 char opt_args_count_oper = '\0';
2251 unsigned opt_args_count_mark = 0;
2252 int opt_optional_args = 0;
2253 int opt_eval_first = 0;
2255 int n;
2256 int pos;
2257 int count = 0;
2259 char * s_orig = s;
2261 char * p;
2262 char * opt_name;
2263 char * next_ctx;
2264 char token[65];
2266 *opt = NULL;
2267 memset(opt_arg, '\0', 33);
2269 /* Strip the leading blanks. */
2270 /* """"""""""""""""""""""""" */
2271 while (isblank(*s))
2272 s++;
2274 if (*s == '[') /* Start of an optional option. */
2276 opt_optional = 1;
2277 s++;
2279 s = strtoken(s, token, sizeof(token) - 1, "[^] \n\t.]", &pos);
2280 if (s == NULL)
2281 return -1; /* Empty string. */
2283 /* Early EOS, only return success if the option is mandatory. */
2284 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2285 if (!*s)
2286 if (opt_optional == 1)
2287 return -(s - s_orig - 1);
2289 /* Validate the option name */
2290 /* ALPHA+(ALPHANUM|_)* */
2291 /* """""""""""""""""""""""" */
2292 p = token;
2293 if (!isalpha(*p) && *p != '*')
2294 return -(s - s_orig - 1); /* opt_name must start with a letter. */
2296 if (*p == '*')
2297 opt_eval_first = 1;
2299 p++;
2300 while (*p)
2302 if (!isalnum(*p) && *p != '_' && *p != '>')
2303 return -(s - s_orig - 1); /* opt_name must contain a letter, *
2304 * a number or a _ */
2305 p++;
2308 if (opt_eval_first)
2309 opt_name = xstrdup(token + 1); /* Ignore the first '*' in token. */
2310 else
2311 opt_name = xstrdup(token);
2313 if (*s == ']')
2315 s++;
2316 while (isblank(*s))
2317 s++;
2319 goto success;
2322 /* Check if it can appear multiple times by looking for the dots. */
2323 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2324 p = strtoken(s, token, 3, "[.]", &pos);
2325 if (p)
2327 if (strcmp(token, "...") == 0)
2329 opt_multiple = 1;
2330 s = p;
2331 if (*s == '<' || *s == '=' || *s == '>')
2333 unsigned value;
2334 int offset;
2336 n = sscanf(s + 1, "%u%n", &value, &offset);
2337 if (n == 1)
2339 opt_count_matter = 1;
2340 opt_count_oper = *s;
2341 opt_count_mark = value;
2343 s += offset + 1;
2346 else
2348 free(opt_name);
2349 return -(s - s_orig - 1);
2353 /* A blank separates the option name and the argument tag. */
2354 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""" */
2355 if (isblank(*s))
2357 char dots[4];
2359 while (isblank(*s))
2360 s++;
2362 if (!*s)
2363 goto success;
2365 pos = 0;
2366 n = sscanf(s, "[%32[^] .\t]%n%3[.]", opt_arg, &pos, dots);
2367 if (pos > 1 && *opt_arg == '#') /* [# has been read. */
2369 opt_args = 1;
2370 opt_optional_args = 1;
2371 if (n == 2)
2372 opt_multiple_args = 1; /* There were dots. */
2374 s += pos + !!(n == 2) * 3; /* Skips the dots. */
2376 if (*s == '<' || *s == '=' || *s == '>')
2378 unsigned value;
2379 int offset;
2381 n = sscanf(s + 1, "%u%n", &value, &offset);
2382 if (n == 1)
2384 opt_args_count_matter = 1;
2385 opt_args_count_oper = *s;
2386 opt_args_count_mark = value;
2388 s += offset + 1;
2391 /* Optional arg tag must end with a ] */
2392 /* """""""""""""""""""""""""""""""""" */
2393 if (*s != ']')
2395 free(opt_name);
2396 return -(s - s_orig - 1);
2399 s++; /* Skip the ] */
2401 else
2403 n = sscanf(s, "%32[^] .\t]%n%3[.]", opt_arg, &pos, dots);
2404 if (pos > 0 && *opt_arg == '#') /* # has been read. */
2406 opt_args = 1;
2407 if (n == 2) /* There were dots. */
2408 opt_multiple_args = 1;
2410 s += pos + !!(n == 2) * 3; /* Skip the dots */
2412 if (*s == '<' || *s == '=' || *s == '>')
2414 unsigned value;
2415 int offset;
2417 n = sscanf(s + 1, "%u%n", &value, &offset);
2418 if (n == 1)
2420 opt_args_count_matter = 1;
2421 opt_args_count_oper = *s;
2422 opt_args_count_mark = value;
2424 s += offset + 1;
2428 if (*s == ']')
2430 /* Abort on extraneous ] if the option is mandatory. */
2431 /* """"""""""""""""""""""""""""""""""""""""""""""""" */
2432 if (!opt_optional)
2433 return -(s - s_orig - 1);
2435 s++; /* skip the ] */
2437 /* Strip the following blanks. */
2438 /* """"""""""""""""""""""""""" */
2439 while (isblank(*s))
2440 s++;
2442 goto success;
2444 else if (opt_optional == 0 && (!*s || isblank(*s)))
2446 /* Strip the following blanks. */
2447 /* """"""""""""""""""""""""""" */
2448 while (isblank(*s))
2449 s++;
2451 goto success;
2453 else if (opt_args == 0) /* # was not read it is possibly the start *
2454 * of another option. */
2455 goto success;
2456 else
2457 return -(s - s_orig - 1);
2460 success:
2462 /* Strip the following blanks. */
2463 /* """"""""""""""""""""""""""" */
2464 while (isblank(*s))
2465 s++;
2467 next_ctx = NULL;
2469 if (*opt_name == '>')
2470 fatal_internal("The option name is missing in %s.", opt_name);
2472 count = strchrcount(opt_name, '>');
2473 if (count == 1)
2475 char * tmp = strchr(opt_name, '>');
2476 next_ctx = xstrdup(tmp + 1);
2477 *tmp = '\0';
2479 else if (count > 1)
2480 fatal_internal("Only one occurrence of '>' is allowed in %s.", opt_name);
2482 *opt = xmalloc(sizeof(opt_t));
2484 (*opt)->name = opt_name;
2485 (*opt)->optional = opt_optional;
2486 (*opt)->multiple = opt_multiple;
2487 (*opt)->opt_count_matter = opt_count_matter;
2488 (*opt)->opt_count_oper = opt_count_oper;
2489 (*opt)->opt_count_mark = opt_count_mark;
2490 (*opt)->args = opt_args;
2491 (*opt)->arg = xstrdup(opt_arg);
2492 (*opt)->optional_args = opt_optional_args;
2493 (*opt)->multiple_args = opt_multiple_args;
2494 (*opt)->opt_args_count_matter = opt_args_count_matter;
2495 (*opt)->opt_args_count_oper = opt_args_count_oper;
2496 (*opt)->opt_args_count_mark = opt_args_count_mark;
2497 (*opt)->eval_first = opt_eval_first;
2498 (*opt)->next_ctx = next_ctx;
2499 (*opt)->ctx_list = ll_new();
2500 (*opt)->constraints_list = ll_new();
2501 (*opt)->action = NULL;
2502 (*opt)->params = NULL;
2503 (*opt)->data = NULL;
2505 return s - s_orig;
2508 /* ==================================================================== */
2509 /* Try to initialize all the option in a given string */
2510 /* Each parsed option are put in a BST tree with its name as index. */
2511 /* */
2512 /* On collision, the arguments only the signature are required to be */
2513 /* the same else this is considered as an error. Options can be used in */
2514 /* more than one context and can be optional in one and mandatory in */
2515 /* another. */
2516 /* ==================================================================== */
2517 static int
2518 init_opts(char * spec, ctx_t * ctx)
2520 opt_t * opt, *bst_opt;
2521 bst_t * node;
2522 int offset;
2524 while (*spec)
2526 if ((offset = opt_parse(spec, &opt)) > 0)
2528 spec += offset;
2530 if ((node = bst_find(opt, &options_bst, opt_compare)) != NULL)
2532 int same_next_ctx = 0;
2534 bst_opt = node->key; /* Node extracted from the BST. */
2536 if (bst_opt->next_ctx == NULL && opt->next_ctx == NULL)
2537 same_next_ctx = 1;
2538 else if (bst_opt->next_ctx == NULL && opt->next_ctx != NULL)
2539 same_next_ctx = 0;
2540 else if (bst_opt->next_ctx != NULL && opt->next_ctx == NULL)
2541 same_next_ctx = 0;
2542 else
2543 same_next_ctx = strcmp(bst_opt->next_ctx, opt->next_ctx) == 0;
2545 if (bst_opt->optional_args != opt->optional_args
2546 || bst_opt->multiple_args != opt->multiple_args
2547 || bst_opt->args != opt->args || !same_next_ctx)
2549 fatal_internal("The option %s already exists with "
2550 "a different arguments signature.\n",
2551 opt->name);
2554 /* The newly created opt is already present in options_bst. */
2555 /* We can remove it. */
2556 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2557 opt_free(opt);
2559 /* The new occurrence of the option option is legal */
2560 /* append the current context ptr in the list. */
2561 /* """""""""""""""""""""""""""""""""""""""""""""""" */
2562 ll_append(bst_opt->ctx_list, ctx);
2564 /* Append the new option to the context's options list. */
2565 /* """""""""""""""""""""""""""""""""""""""""""""""""""" */
2566 ll_append(ctx->opt_list, bst_opt);
2568 else
2570 /* Initialize the option's context list with the current context. */
2571 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2572 ll_append(opt->ctx_list, ctx);
2574 /* Append the new option to the context's options list. */
2575 /* """""""""""""""""""""""""""""""""""""""""""""""""""" */
2576 ll_append(ctx->opt_list, opt);
2578 /* Insert the new option in the BST. */
2579 /* """"""""""""""""""""""""""""""""" */
2580 bst_search(opt, &options_bst, opt_compare);
2583 else
2585 char * s = xstrndup(spec, -offset);
2586 printf("%s <---\nSyntax error at or before offset %d\n", s, -offset);
2587 free(s);
2589 exit(EXIT_FAILURE);
2593 return 1;
2596 /* ===================================================== */
2597 /* ctxopt initialization function, must be called first. */
2598 /* ===================================================== */
2599 void
2600 ctxopt_init(char * prog_name, char * init_flags)
2602 int n;
2604 contexts_bst = NULL;
2605 options_bst = NULL;
2606 char * ptr;
2608 user_rc = 0;
2609 user_value = 0;
2610 user_string = xmalloc(8);
2611 user_string2 = xmalloc(8);
2612 user_object = NULL;
2613 char flag[33], fname[31], vname[31];
2614 int invalid;
2616 ctxopt_initialized = 1;
2618 /* Initialize current_state.*/
2619 /* """""""""""""""""""""""" */
2620 cur_state = xcalloc(sizeof(state_t), 0);
2622 /* Initialize custom error function pointers to NULL. */
2623 /* """""""""""""""""""""""""""""""""""""""""""""""""" */
2624 err_functions = xmalloc(CTXOPTERRSIZ * sizeof(void *));
2625 for (n = 0; n < CTXOPTERRSIZ; n++)
2626 err_functions[n] = NULL;
2628 /* Parse init_flags if any. */
2629 /* """""""""""""""""""""""" */
2630 while (*init_flags && (init_flags = get_word(init_flags, flag, 32)))
2632 if (*flag)
2634 if (sscanf(flag, "%30[^=]=%30[^=]", fname, vname) != 2)
2635 fatal_internal("Invalid flag assignment: %s.", flag);
2637 if (strcmp(fname, "stop_if_non_option") == 0)
2639 if (eval_yes(vname, &invalid))
2640 flags.stop_if_non_option = 1;
2641 else if (!invalid)
2642 flags.stop_if_non_option = 0;
2643 else
2644 fatal_internal("Invalid flag value for %s: %s.", fname, vname);
2646 else if (strcmp(fname, "allow_abbreviations") == 0)
2648 if (eval_yes(vname, &invalid))
2649 flags.allow_abbreviations = 1;
2650 else if (!invalid)
2651 flags.allow_abbreviations = 0;
2652 else
2653 fatal_internal("Invalid flag value for %s: %s.", fname, vname);
2655 else
2656 fatal_internal("Invalid flag name: %s.", fname);
2660 /* Update current_state. */
2661 /* """"""""""""""""""""" */
2662 if (prog_name)
2664 if (*prog_name == '\0')
2665 cur_state->prog_name = xstrdup("program_name");
2666 else if ((ptr = strrchr(prog_name, '/')))
2667 cur_state->prog_name = xstrdup(ptr + 1);
2668 else
2669 cur_state->prog_name = xstrdup(prog_name);
2671 else
2672 cur_state->prog_name = xstrdup("program_name");
2675 /* ========================================================================= */
2676 /* Utility function which create and register a par_t object in a BST */
2677 /* embedded in a context. */
2678 /* This object will have a name and a pointer to the option it refers to. */
2679 /* These object will be used to quickly find an option from a command */
2680 /* line parameter during the analysis phase. */
2681 /* */
2682 /* IN : an option name. */
2683 /* IN : a string of command line parameters to associate to the option. */
2684 /* Returns : 1 is all was fine else 0. */
2685 /* ========================================================================= */
2686 static int
2687 opt_set_parms(char * opt_name, char * par_str)
2689 char * par_name, *ctx_name;
2690 char * tmp_par_str, *end_tmp_par_str;
2691 ctx_t * ctx;
2692 opt_t * opt;
2693 bst_t * node;
2694 par_t * par, tmp_par;
2695 int rc = 1; /* return code */
2697 ll_t * list;
2698 ll_node_t * lnode;
2700 /* Look if the given option is defined. */
2701 /* """""""""""""""""""""""""""""""""""" */
2702 opt = locate_opt(opt_name);
2703 if (opt == NULL)
2704 fatal_internal("Unknown option %s.", opt_name);
2706 /* For each context using this option. */
2707 /* """"""""""""""""""""""""""""""""""" */
2708 list = opt->ctx_list;
2710 lnode = list->head;
2711 while (lnode != NULL)
2713 /* Locate the context in the contexts tree. */
2714 /* """""""""""""""""""""""""""""""""""""""" */
2715 ctx_name = ((ctx_t *)(lnode->data))->name;
2717 ctx = locate_ctx(ctx_name);
2718 if (ctx == NULL)
2719 fatal_internal("Unknown context %s.", ctx_name);
2720 else
2722 void * par_bst = ctx->par_bst;
2724 tmp_par_str = xstrdup(par_str);
2725 ltrim(tmp_par_str, " \t");
2726 rtrim(tmp_par_str, " \t", 0);
2727 par_name = xstrtok_r(tmp_par_str, " \t,", &end_tmp_par_str);
2728 if (par_name == NULL)
2729 fatal_internal("Parameters are missing for option %s.", opt_name);
2731 /* For each parameter given in par_str, creates a par_t object and */
2732 /* insert it the in the parameters BST of the context. */
2733 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2734 while (par_name != NULL)
2736 tmp_par.name = par_name;
2738 node = bst_find(&tmp_par, &par_bst, par_compare);
2739 if (node != NULL)
2741 fatal_internal("The parameter %s is already defined in context %s.",
2742 par_name, ctx->name);
2743 rc = 0;
2745 else
2747 par = xmalloc(sizeof(par_t));
2748 par->name = xstrdup(par_name);
2749 par->opt = opt; /* Link the option to this parameter */
2751 bst_search(par, &par_bst, par_compare);
2753 par_name = xstrtok_r(NULL, " \t,", &end_tmp_par_str);
2756 /* Update the value of the root of ctx->par_bst as it may have */
2757 /* been modified. */
2758 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2759 ctx->par_bst = par_bst;
2761 free(tmp_par_str);
2763 lnode = lnode->next;
2766 return rc;
2769 /* ==================================================================== */
2770 /* Create a new context instance. */
2771 /* IN ctx : a context pointer to allow this instance to */
2772 /* access the context fields */
2773 /* IN prev_ctx_inst : the context instance whose option leading to the */
2774 /* creation of this new context instance is part of */
2775 /* Returns : the new context. */
2776 /* ==================================================================== */
2777 static ctx_inst_t *
2778 new_ctx_inst(ctx_t * ctx, ctx_inst_t * prev_ctx_inst)
2780 opt_t * opt;
2781 opt_inst_t * gen_opt_inst;
2782 ctx_inst_t * ctx_inst;
2783 seen_opt_t * seen_opt;
2784 char * str, *opt_name;
2785 void * bst;
2786 bst_t * bst_node;
2788 /* Keep a trace of the opt_inst which was at the origin of the creation */
2789 /* of this context instance. */
2790 /* This will serve during the evaluation of the option callbacks. */
2791 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2792 if (prev_ctx_inst != NULL)
2794 gen_opt_inst = (opt_inst_t *)(prev_ctx_inst->opt_inst_list->tail->data);
2796 /* Update current_state. */
2797 /* """"""""""""""""""""" */
2798 cur_state->opt_name = gen_opt_inst->opt->name;
2800 else
2801 gen_opt_inst = NULL;
2803 /* Create and initialize the new context instance. */
2804 /* """"""""""""""""""""""""""""""""""""""""""""""" */
2805 ctx_inst = xmalloc(sizeof(ctx_inst_t));
2806 ctx_inst->ctx = ctx;
2807 ctx_inst->prev_ctx_inst = prev_ctx_inst;
2808 ctx_inst->gen_opt_inst = gen_opt_inst;
2809 ctx_inst->incomp_bst_list = ll_new();
2810 ctx_inst->opt_inst_list = ll_new();
2811 ctx_inst->seen_opt_bst = NULL;
2813 ll_node_t * node;
2815 if (prev_ctx_inst == NULL)
2816 first_ctx_inst = ctx_inst;
2818 /* Initialize the occurrence counters of each opt allowed in the context. */
2819 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2820 node = ctx->opt_list->head;
2821 while (node != NULL)
2823 opt = node->data;
2824 opt->occurrences = 0;
2826 node = node->next;
2829 /* Initialize the BST containing the seen indicator for all the options */
2830 /* allowed in this context instance. */
2831 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2832 node = ctx->opt_list->head;
2833 while (node != NULL)
2835 opt = node->data;
2836 seen_opt = xmalloc(sizeof(seen_opt_t));
2837 seen_opt->opt = opt;
2838 seen_opt->par = NULL;
2839 seen_opt->seen = 0;
2841 bst_search(seen_opt, &(ctx_inst->seen_opt_bst), seen_opt_compare);
2843 node = node->next;
2846 /* Initialize the BST containing the incompatibles options. */
2847 /* Incompatibles option names are read from strings found in the list */
2848 /* incomp_list present in each instance of ctx_t. */
2849 /* These names are then used to search for the object of type seen_opt_t */
2850 /* which is already present in the seen_opt_bst of the context instance. */
2851 /* in the BST. */
2852 /* Once found the seen_opt_t object in inserted in the new BST */
2853 /* At the end the new BST in added to the list incomp_bst_list. */
2854 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2855 node = ctx->incomp_list->head;
2856 while (node != NULL)
2858 bst = NULL;
2859 seen_opt_t tmp_seen_opt;
2861 str = xstrdup(node->data);
2862 ltrim(str, " \t");
2863 rtrim(str, " \t", 0);
2864 opt_name = strtok(str, " \t"); /* Extract the first option name. */
2866 while (opt_name != NULL) /* For each option name. */
2868 if ((opt = locate_opt(opt_name)) != NULL)
2870 /* The option found is searched in the tree of potential */
2871 /* seen options. */
2872 /* """"""""""""""""""""""""""""""""""""""""""""""""""""" */
2873 tmp_seen_opt.opt = opt;
2875 bst_node = bst_find(&tmp_seen_opt, &(ctx_inst->seen_opt_bst),
2876 seen_opt_compare);
2878 if (bst_node != NULL)
2880 /* If found then it is added into the new BST tree. */
2881 /* """""""""""""""""""""""""""""""""""""""""""""""" */
2882 seen_opt = bst_node->key;
2883 bst_search(seen_opt, &bst, seen_opt_compare);
2885 else
2886 /* Not found! That means that the option is unknown in this */
2887 /* context as all options has have a seen_opt structure in */
2888 /* seen_opt_bst. */
2889 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2890 fatal_internal("%s is not known in the context %s.", opt->name,
2891 ctx->name);
2893 else
2894 fatal_internal("Unknown option %s.", opt_name);
2896 opt_name = strtok(NULL, " \t");
2899 free(str);
2900 ll_append(ctx_inst->incomp_bst_list, bst);
2902 node = node->next;
2905 return ctx_inst;
2908 /* ====================================================================== */
2909 /* Create a list formed by all the significant command line words */
2910 /* Words beginning or ending with { or } are split. Each of these */
2911 /* symbols will get their own place in the list. */
2912 /* */
2913 /* the {...} part delimits a context, the { will not appear in the list */
2914 /* and the } will be replaced by a | in the resulting list (cmdline_list) */
2915 /* to facilitate the parsing phase. | must not be used by the end user. */
2916 /* */
2917 /* IN nb_word : number of word to parse, this is typically argc-1 as the */
2918 /* program name is not considered. */
2919 /* IN words : is the array of strings constituting the command line to */
2920 /* parse. */
2921 /* Returns : 1 on success, 0 if a { or } is missing. */
2922 /* ====================================================================== */
2923 static int
2924 ctxopt_build_cmdline_list(int nb_words, char ** words)
2926 int i;
2927 char * prev_word = NULL;
2928 char * word;
2929 char * ptr;
2930 int level = 0;
2931 ll_node_t *node, *start_node;
2933 /* The analysis is divided into three passes, this is not optimal but */
2934 /* must be done only one time. Doing that we privilege readability. */
2935 /* */
2936 /* In the following, SG is the ascii character 1d (dec 29) */
2937 /* */
2938 /* The first pass creates the list, extract the leading an trailing */
2939 /* SG '{' and '}' of each word and give them their own place in the */
2940 /* list */
2941 /* */
2942 /* The second pass transform the '{...}' blocks by a trailing SG */
2943 /* ({...} -> ...|) */
2944 /* */
2945 /* The last pass remove the duplicated SG, check for SG, '{' or '}' in */
2946 /* the middle in the remaining list elements and recreate the pseudo */
2947 /* argument: {} */
2948 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2950 /* If the option list is not empty, clear it before going further. */
2951 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2952 if (cmdline_list != NULL)
2954 node = cmdline_list->head;
2955 while (node != NULL)
2957 free(node->data);
2958 ll_delete(cmdline_list, node);
2959 node = cmdline_list->head;
2962 else
2963 cmdline_list = ll_new();
2965 start_node = cmdline_list->head; /* In the following loop start_node will *
2966 * contain a pointer to the current *
2967 * word stripped from its leading *
2968 * sequence of {, }. */
2969 for (i = 0; i < nb_words; i++)
2971 size_t len = strlen(words[i]);
2972 size_t start, end;
2973 char * str;
2975 str = words[i];
2977 /* Replace each occurrence of the legal word {} by the characters */
2978 /* 0x02 and 0x03 to hide them from the following process. */
2979 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2980 while ((ptr = strstr(str, "{}")) != NULL)
2982 *ptr = 0x02; /* Arbitrary values unlikely. */
2983 *(ptr + 1) = 0x03; /* present in a word */
2986 if (len > 1) /* The word contains at least 2 characters. */
2988 start = 0;
2990 /* Interpret its beginning and look for the start of the real word. */
2991 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2992 while (start <= len - 1 && (str[start] == '{' || str[start] == '}'))
2994 ll_append(cmdline_list, xstrndup(str + start, 1));
2995 start++;
2996 start_node = cmdline_list->tail;
2999 end = len - 1;
3000 if (str[end] == '{' || str[end] == '}')
3002 if (end > 0 && str[end - 1] != '\\')
3004 ll_append(cmdline_list, xstrndup(str + end, 1));
3005 end--;
3006 node = cmdline_list->tail;
3008 while (str[end] == '{' || str[end] == '}')
3010 if (end > start && str[end - 1] == '\\')
3011 break;
3013 ll_insert_before(cmdline_list, node, xstrndup(str + end, 1));
3014 end--;
3015 node = node->prev;
3020 if (start <= end)
3022 if (start_node != NULL)
3023 ll_insert_after(cmdline_list, start_node,
3024 xstrndup(str + start, end - start + 1));
3025 else
3026 ll_append(cmdline_list, xstrndup(str + start, end - start + 1));
3027 start_node = cmdline_list->tail;
3030 else if (len == 1)
3032 ll_append(cmdline_list, xstrdup(str));
3033 start_node = cmdline_list->tail;
3037 /* 2nd pass. */
3038 /* """"""""" */
3039 node = cmdline_list->head;
3041 level = 0;
3042 while (node != NULL)
3044 word = node->data;
3046 if (strcmp(word, "{") == 0)
3048 ll_node_t * old_node = node;
3049 level++;
3050 node = node->next;
3051 free(word);
3052 ll_delete(cmdline_list, old_node);
3054 else if (strcmp(word, "}") == 0)
3056 level--;
3058 if (level < 0)
3059 return 0;
3060 else
3061 *word = 0x1d;
3063 else
3064 node = node->next;
3067 if (level != 0)
3068 return 0;
3070 /* 3rd pass. */
3071 /* """"""""" */
3072 node = cmdline_list->head;
3074 while (node != NULL)
3076 word = node->data;
3078 /* Restore the original { and } characters forming the legal word {}. */
3079 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3080 while ((ptr = strchr(word, 0x02)) != NULL)
3081 *ptr = '{';
3082 while ((ptr = strchr(word, 0x03)) != NULL)
3083 *ptr = '}';
3085 /* Remove a SG if the previous element is SG. */
3086 /* """""""""""""""""""""""""""""""""""""""""" */
3087 if (strcmp(word, "\x1d") == 0)
3089 if (prev_word != NULL && (strcmp(prev_word, "\x1d") == 0))
3091 ll_node_t * old_node = node;
3092 node = node->prev;
3093 free(old_node->data);
3094 ll_delete(cmdline_list, old_node);
3097 else if (strcmp(word, "-") == 0) /* A single - is a legal argument, not *
3098 * a parameter. Protect it. */
3100 free(node->data);
3101 node->data = xstrdup("\\-");
3104 prev_word = node->data;
3105 node = node->next;
3108 /* Clean useless and SG at the beginning and end of list. */
3109 /* """""""""""""""""""""""""""""""""""""""""""""""""""""" */
3110 node = cmdline_list->head;
3112 if (node == NULL)
3113 return 1;
3115 word = node->data;
3117 if (strcmp(word, "\x1d") == 0)
3119 free(word);
3120 ll_delete(cmdline_list, node);
3123 node = cmdline_list->tail;
3124 if (node == NULL)
3125 return 1;
3127 word = node->data;
3129 if (strcmp(word, "\x1d") == 0)
3131 free(word);
3132 ll_delete(cmdline_list, node);
3135 return 1;
3138 /* ===================================================================== */
3139 /* Build and analyze the command line list and create the linked data */
3140 /* structures whose data will be evaluated later by ctxopt_evaluate. */
3141 /* This function identifies the following errors and creates an array of */
3142 /* The remaining unanalyzed arguments. */
3143 /* - detect missing arguments */
3144 /* - detect too many arguments */
3145 /* - detect unknown parameters in a context */
3146 /* - detect too many occurrences of a parameters in a context */
3147 /* - detect missing required arguments in a context */
3148 /* */
3149 /* IN nb_word : number of word to parse, this is typically argc-1 as the */
3150 /* program name is not considered */
3151 /* IN words : is the array of strings constituting the command line to */
3152 /* parse. */
3153 /* OUT nb_rem_args : nb of remaining command line arguments if a -- */
3154 /* is present in the list. */
3155 /* OUT rem_args : array of remaining command line arguments if a -- */
3156 /* is present in the list. This array must be free by */
3157 /* The caller as it is allocated here. */
3158 /* ===================================================================== */
3159 void
3160 ctxopt_analyze(int nb_words, char ** words, int * nb_rem_args,
3161 char *** rem_args)
3163 ctx_t * ctx;
3164 opt_t * opt;
3165 par_t * par;
3166 ctx_inst_t * ctx_inst;
3167 opt_inst_t * opt_inst;
3168 int expect_par = 0;
3169 int expect_arg = 0;
3170 int expect_par_or_arg = 0;
3172 ll_node_t * cli_node;
3173 bst_t * bst_node;
3174 seen_opt_t * bst_seen_opt;
3175 char * par_name;
3176 void * bst;
3178 ll_node_t * node;
3180 if (!ctxopt_build_cmdline_list(nb_words, words))
3181 fatal_internal("The command line could not be parsed: "
3182 "missing '{' or '}' detected.");
3184 if (main_ctx == NULL)
3185 fatal_internal("At least one context must have been created.");
3187 /* Check that all options has an action and at least one parameter. */
3188 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3189 bst_walk(options_bst, bst_check_opt_cb);
3191 /* Create the first ctx_inst record. */
3192 /* """"""""""""""""""""""""""""""""" */
3193 ctx = main_ctx;
3195 ctx_inst_list = ll_new();
3196 ctx_inst = new_ctx_inst(ctx, NULL);
3197 ctx_inst->par_name = NULL;
3199 /* Update current_state. */
3200 /* """"""""""""""""""""" */
3201 cur_state->ctx_name = ctx->name;
3203 ll_append(ctx_inst_list, ctx_inst);
3205 /* For each node in the command line. */
3206 /* """""""""""""""""""""""""""""""""" */
3207 cli_node = cmdline_list->head;
3208 expect_par = 1;
3209 while (cli_node != NULL)
3211 if (strcmp(cli_node->data, "--") == 0)
3212 break; /* No new parameter will be analyzed after this point. */
3214 par_name = cli_node->data;
3216 /* Replace a leading -- by a single - */
3217 /* """""""""""""""""""""""""""""""""" */
3218 if (strncmp(cli_node->data, "--", 2) == 0)
3219 par_name += 1; /* Ignore the first dash */
3221 if (strcmp(par_name, "\x1d") == 0)
3223 check_for_missing_mandatory_opt(ctx_inst, (char *)(cli_node->prev->data));
3224 check_for_occurrences_issues(ctx_inst);
3226 /* Forced backtracking to the previous context instance. */
3227 /* """"""""""""""""""""""""""""""""""""""""""""""""""""" */
3228 if (ctx_inst->prev_ctx_inst != NULL)
3230 ctx_inst = ctx_inst->prev_ctx_inst;
3231 ctx = ctx_inst->ctx;
3233 /* Update current_states. */
3234 /* """"""""""""""""""""" */
3235 cur_state->ctx_name = ctx->name;
3236 cur_state->ctx_par_name = ctx_inst->par_name;
3238 else
3240 /* Update current_state. */
3241 /* """"""""""""""""""""" */
3242 cur_state->ctx_par_name = NULL;
3245 else if (expect_par && *par_name == '-')
3247 int pos = 0;
3248 char * prefix;
3250 /* Update current_state. */
3251 /* """"""""""""""""""""" */
3252 cur_state->cur_opt_par_name = par_name;
3253 cur_state->ctx_name = ctx->name;
3254 cur_state->ctx_par_name = ctx_inst->par_name;
3256 /* An expected parameter has been seen. */
3257 /* """""""""""""""""""""""""""""""""""" */
3258 if ((par = locate_par(par_name, ctx)) == NULL)
3260 opt_t * popt;
3261 char * word;
3263 /* Look if this parameter is an unique abbreviation of a longer */
3264 /* parameter. If this is the case then just replace it with its */
3265 /* full length version and try again. */
3266 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3267 if (flags.allow_abbreviations)
3268 if ((word = abbrev_expand(par_name, ctx)) != NULL)
3270 cli_node->data = word;
3271 continue;
3274 /* Try to find a prefix which is a valid parameter in this context */
3275 /* If found, split the cli_node in two to build a new parameter */
3276 /* node and followed by a node containing the remaining string */
3277 /* If the new parameter corresponds to an option not taking */
3278 /* argument then prefix the remaining string whit a dash as it may */
3279 /* contain a new parameter. */
3280 /* The new parameter will be re-evaluated in the next iteration of */
3281 /* the loop. */
3282 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""*/
3283 prefix = look_for_valid_prefix_in_word(par_name, ctx, &pos, &popt);
3284 if (prefix != NULL && pos != 0)
3286 cli_node->data = prefix; /* prefix contains le name of a valid *
3287 | parameter in this context. */
3289 if (popt->args)
3291 /* The parameter may be followed by arguments. */
3292 /* ''''''''''''''''''''''''''''''''''''''''''' */
3293 if (*(par_name + pos) == '-')
3295 word = xstrdup("\\"); /* Protect the '-' */
3296 word = strappend(word, par_name + pos, NULL);
3298 else
3299 word = xstrdup(par_name + pos);
3301 else
3303 /* The parameter does not take arguments, the */
3304 /* following word must be a parameter or nothing */
3305 /* hence prefix it with a dash. */
3306 /* ''''''''''''''''''''''''''''''''''''''''''''' */
3307 word = xstrdup("-");
3308 word = strappend(word, par_name + pos, NULL);
3311 /* Insert it after the current node in the list. */
3312 /* """"""""""""""""""""""""""""""""""""""""""""" */
3313 ll_insert_after(cmdline_list, cli_node, word);
3315 continue; /* loop */
3317 else
3319 check_for_missing_mandatory_opt(ctx_inst, par_name);
3320 check_for_occurrences_issues(ctx_inst);
3322 if (ctx_inst->prev_ctx_inst == NULL)
3324 char * errmsg = xstrdup("");
3326 /* Update current_state. */
3327 /* """"""""""""""""""""" */
3328 cur_state->ctx_par_name = NULL;
3330 *user_string = '\0';
3331 *user_string2 = '\0';
3333 user_string = strappend(user_string, par_name, NULL);
3335 bst_walk(contexts_bst, bst_match_par_cb);
3337 if (*user_string2 != '\0')
3339 errmsg = strappend(
3340 errmsg,
3341 "\nIt appears to be defined in the context(s):", user_string2,
3342 "\n", NULL);
3345 fatal(CTXOPTUNKPAR, errmsg);
3347 else
3349 /* Tries to backtrack and analyse the same parameter in the */
3350 /* previous context. */
3351 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3352 ctx_inst = ctx_inst->prev_ctx_inst;
3353 ctx = ctx_inst->ctx;
3355 /* Update current_state. */
3356 /* """"""""""""""""""""" */
3357 cur_state->ctx_name = ctx->name;
3358 cur_state->ctx_par_name = ctx_inst->par_name;
3360 cli_node = cli_node->prev;
3364 else
3366 seen_opt_t seen_opt;
3368 /* The parameter is valid in the context, create a opt_inst and */
3369 /* append it to the ctx_inst list options list. */
3370 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3371 opt = par->opt;
3373 opt->occurrences++;
3375 opt_inst = xmalloc(sizeof(opt_inst_t));
3376 opt_inst->opt = opt;
3377 opt_inst->par = par_name;
3378 opt_inst->values_list = ll_new();
3379 opt_inst->next_ctx_inst = NULL;
3381 /* Update current_state. */
3382 /* """"""""""""""""""""" */
3383 cur_state->cur_opt_params = opt->params;
3385 /* Priority option are inserted at the start of the opt_inst list */
3386 /* but their order of appearance in the context definition must */
3387 /* be preserver so each new priority option will be placed after */
3388 /* the previous ones at the start of the opt_inst list. */
3389 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3390 if (!opt->eval_first)
3391 ll_append(ctx_inst->opt_inst_list, opt_inst);
3392 else
3394 ll_node_t * opt_inst_node = ctx_inst->opt_inst_list->head;
3395 opt_inst_t * tmp_opt_inst;
3397 while (opt_inst_node != NULL)
3399 tmp_opt_inst = opt_inst_node->data;
3400 if (!tmp_opt_inst->opt->eval_first)
3402 ll_insert_before(ctx_inst->opt_inst_list, opt_inst_node,
3403 opt_inst);
3404 break;
3406 else
3407 opt_inst_node = opt_inst_node->next;
3409 if (opt_inst_node == NULL)
3410 ll_append(ctx_inst->opt_inst_list, opt_inst);
3413 /* Check if an option was already seen in the */
3414 /* current context instance. */
3415 /* """""""""""""""""""""""""""""""""""""""""" */
3416 seen_opt.opt = opt;
3418 bst_node = bst_find(&seen_opt, &(ctx_inst->seen_opt_bst),
3419 seen_opt_compare);
3421 /* bst_node cannot be NULL here. */
3423 bst_seen_opt = (seen_opt_t *)(bst_node->key);
3425 if (!opt->multiple && bst_seen_opt->seen == 1)
3426 fatal(CTXOPTDUPOPT, NULL);
3428 /* Check if this option is compatible with the options already */
3429 /* seen in this context instance. */
3430 /* Look if the option is present in one on the BST present in */
3431 /* the incomp_bst_list of the context instance. */
3432 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3433 node = ctx_inst->incomp_bst_list->head;
3434 while (node != NULL)
3436 bst = node->data;
3437 user_object = NULL;
3439 /* There can only have one seen_opt object in the BST tree was */
3440 /* already seen, try to locate it, the result will be put in */
3441 /* user_object by the bst_seen_opt_seen_cb function. */
3442 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3443 bst_walk(bst, bst_seen_opt_seen_cb);
3445 /* If it is the case, look if the current option is also */
3446 /* in this BST. */
3447 /* """"""""""""""""""""""""""""""""""""""""""""""""""""" */
3448 if (user_object != NULL)
3450 bst_node = bst_find(bst_seen_opt, &bst, seen_opt_compare);
3452 if (bst_node != NULL)
3454 bst_seen_opt = (seen_opt_t *)(bst_node->key);
3455 if (bst_seen_opt->seen == 0)
3456 fatal(CTXOPTINCOPT, (char *)user_object);
3460 node = node->next;
3463 /* Mark this option as seen in the current context instance. */
3464 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3465 bst_seen_opt->seen = 1;
3466 free(bst_seen_opt->par);
3467 bst_seen_opt->par = xstrdup(par_name);
3469 /* If this option leads to a next context, create a new ctx_inst */
3470 /* and switch to it for the analyse of the future parameter. */
3471 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3472 if (opt->next_ctx != NULL)
3474 ctx = locate_ctx(opt->next_ctx);
3476 if (ctx == NULL)
3477 fatal_internal("Unknown context %s.", opt->next_ctx);
3479 opt_inst->next_ctx_inst = ctx_inst = new_ctx_inst(ctx, ctx_inst);
3480 ctx_inst->par_name = xstrdup(par_name);
3482 ll_append(ctx_inst_list, ctx_inst);
3485 /* Look is we must expect some arguments. */
3486 /* """""""""""""""""""""""""""""""""""""" */
3487 expect_par_or_arg = 0;
3488 expect_par = 0;
3489 expect_arg = 0;
3491 if (!opt->args)
3492 expect_par = 1; /* Parameter doesn't accept any argument. */
3493 else
3495 if (!opt->optional_args)
3496 expect_arg = 1; /* Parameter has mandatory arguments. */
3497 else
3498 expect_par_or_arg = 1; /* Parameter has optional arguments. */
3502 else if (expect_par && *par_name != '-')
3504 ll_node_t * n = cli_node->next;
3506 if (!flags.stop_if_non_option)
3507 /* Look if potential arguments must still be analyzed until the */
3508 /* end of the context/command line part to analyze/command line. */
3509 /* If this is the case we have met an extra argument. */
3510 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3511 while (n != NULL)
3513 if (strcmp(n->data, "--") == 0 || strcmp(n->data, "\x1d") == 0)
3514 fatal(CTXOPTUNXARG, NULL);
3516 if (*(char *)(n->data) == '-')
3517 fatal(CTXOPTUNXARG, NULL);
3519 n = n->next;
3522 break; /* An unexpected non parameter was seen, if no Potential *
3523 | arguments remain in the command line or *
3524 | flags.stop_if_non_option is set, assume that it is is *
3525 | the first of the non arguments and stop the command *
3526 | line analysis. */
3528 else if (expect_arg && *par_name != '-')
3530 ll_node_t * cstr_node;
3531 constraint_t * cstr;
3533 /* Check if the arguments of the option respects */
3534 /* the attached constraints if any. */
3535 /* """"""""""""""""""""""""""""""""""""""""""""" */
3536 cstr_node = opt->constraints_list->head;
3537 while (cstr_node != NULL)
3539 cstr = cstr_node->data;
3540 if (!cstr->constraint(cstr->nb_args, cstr->args, par_name,
3541 cur_state->cur_opt_par_name))
3543 fputs("\n", stderr);
3544 ctxopt_ctx_disp_usage(cur_state->ctx_name, exit_after);
3547 cstr_node = cstr_node->next;
3550 /* If the argument is valid, store it. */
3551 /* """"""""""""""""""""""""""""""""""" */
3552 if (*par_name == '\\' && *(par_name + 1) == '-')
3553 ll_append(opt_inst->values_list, par_name + 1);
3554 else
3555 ll_append(opt_inst->values_list, par_name);
3557 expect_arg = 0;
3558 expect_par = 0;
3559 expect_par_or_arg = 0;
3561 if (opt->multiple_args)
3562 expect_par_or_arg = 1;
3563 else
3564 expect_par = 1; /* Parameter takes only one argument. */
3566 else if (expect_arg && *par_name == '-')
3567 fatal(CTXOPTMISARG, NULL);
3568 else if (expect_par_or_arg)
3570 expect_arg = 0;
3571 expect_par = 0;
3572 expect_par_or_arg = 0;
3574 if (*par_name != '-')
3575 expect_arg = 1; /* Consider this word as an argument and retry. */
3576 else
3577 expect_par = 1; /* Consider this word as a parameter and retry. */
3579 cli_node = cli_node->prev;
3582 cli_node = cli_node->next;
3585 if (cmdline_list->len > 0 && *par_name == '-')
3587 if (expect_arg && !opt->optional_args)
3588 fatal(CTXOPTMISARG, NULL);
3591 /* Look if a context_instance has unseen mandatory options. */
3592 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3593 node = ctx_inst_list->head;
3594 while (node != NULL)
3596 ctx_inst = node->data;
3598 /* Update current_state. */
3599 /* """"""""""""""""""""" */
3600 cur_state->ctx_name = ctx_inst->ctx->name;
3601 cur_state->ctx_par_name = ctx_inst->par_name;
3603 check_for_missing_mandatory_opt(ctx_inst, par_name);
3604 check_for_occurrences_issues(ctx_inst);
3606 node = node->next;
3609 /* Allocate the array containing the remaining not analyzed */
3610 /* command line arguments. */
3611 /* NOTE: The strings in the array are just pointer to the */
3612 /* data of the generating list and must not be freed. */
3613 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3614 if (cli_node != NULL)
3616 if (strcmp((char *)cli_node->data, "--") == 0)
3617 /* The special parameter -- was encountered, the -- argument is not */
3618 /* put in the remaining arguments. */
3619 /* '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' */
3620 ll_strarray(cmdline_list, cli_node->next, nb_rem_args, rem_args);
3621 else
3622 /* A non parameter was encountered when a parameter was expected. We */
3623 /* assume that the evaluation of the remaining command line argument */
3624 /* are not the responsibility of the users code. */
3625 /* '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' */
3626 ll_strarray(cmdline_list, cli_node, nb_rem_args, rem_args);
3628 else
3630 *nb_rem_args = 0;
3631 *rem_args = xmalloc(sizeof(char *));
3632 (*rem_args)[0] = NULL;
3636 /* ==================================================== */
3637 /* Free ctxopt memory used for its internal structures. */
3638 /* ==================================================== */
3639 void
3640 ctxopt_free_memory(void)
3642 ll_destroy(cmdline_list, NULL);
3643 ll_destroy(ctx_inst_list, ctx_inst_free);
3644 bst_destroy(options_bst, opt_free);
3645 bst_destroy(contexts_bst, ctx_free);
3648 /* ==================================================================== */
3649 /* Parse the options data structures and launches the callback function */
3650 /* attached to each options instances. */
3651 /* This calls a recursive function which proceeds context per context. */
3652 /* ==================================================================== */
3653 void
3654 ctxopt_evaluate(void)
3656 evaluate_ctx_inst(first_ctx_inst);
3659 /* =================================================================== */
3660 /* Recursive function called by ctxopt_evaluate to process the list of */
3661 /* the opt_inst present in a ctx_inst and attempt to evaluate the */
3662 /* action attached to the context and its option instances. */
3663 /* =================================================================== */
3664 static void
3665 evaluate_ctx_inst(ctx_inst_t * ctx_inst)
3667 opt_inst_t * opt_inst;
3668 ctx_t * ctx;
3669 opt_t * opt;
3670 ll_node_t * opt_inst_node;
3671 char ** args;
3672 int nb_args;
3674 if (ctx_inst == NULL)
3675 return;
3677 ctx = ctx_inst->ctx;
3679 /* Do not evaluate the action attached to this context is there is no */
3680 /* option to evaluate. */
3681 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3682 opt_inst_node = ctx_inst->opt_inst_list->head;
3683 if (opt_inst_node == NULL)
3684 return;
3686 /* Call the entering action attached to this context if any. */
3687 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3688 if (ctx->action != NULL)
3690 if (ctx_inst->prev_ctx_inst != NULL)
3691 ctx->action(ctx->name, entering, ctx_inst->prev_ctx_inst->ctx->name,
3692 ctx->nb_data, ctx->data);
3693 else
3694 ctx->action(ctx->name, entering, NULL, ctx->nb_data, ctx->data);
3697 /* For each instance of options. */
3698 /* """"""""""""""""""""""""""""" */
3699 while (opt_inst_node != NULL)
3701 opt_inst = (opt_inst_t *)(opt_inst_node->data);
3702 ll_strarray(opt_inst->values_list, opt_inst->values_list->head, &nb_args,
3703 &args);
3704 opt = opt_inst->opt;
3706 /* Launch the attached action if any. */
3707 /* """""""""""""""""""""""""""""""""" */
3708 if (opt->action != NULL)
3709 opt->action(ctx->name, opt->name, opt_inst->par, nb_args, args,
3710 opt->nb_data, opt->data, ctx->nb_data, ctx->data);
3712 if (opt_inst->next_ctx_inst != NULL)
3713 evaluate_ctx_inst(opt_inst->next_ctx_inst);
3715 if (args != NULL)
3716 free(args);
3718 opt_inst_node = opt_inst_node->next;
3721 /* Call the exiting action attached to this context if any. */
3722 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3723 if (ctx->action != NULL)
3725 if (ctx_inst->prev_ctx_inst != NULL)
3726 ctx->action(ctx->name, exiting, ctx_inst->prev_ctx_inst->ctx->name,
3727 ctx->nb_data, ctx->data);
3728 else
3729 ctx->action(ctx->name, exiting, NULL, ctx->nb_data, ctx->data);
3733 /* ============================================================ */
3734 /* Create and initializes a new context. */
3735 /* - allocate space. */
3736 /* - name it. */
3737 /* - initialize its option with a few of their characteristics. */
3738 /* ============================================================ */
3739 void
3740 ctxopt_new_ctx(char * name, char * opts_specs)
3742 ctx_t * ctx;
3743 char * p;
3745 if (!ctxopt_initialized)
3746 fatal_internal("Please call ctxopt_init first.");
3748 ctx = xmalloc(sizeof(ctx_t));
3750 /* Validates the context name: */
3751 /* ALPHA+(ALPHANUM|_)* */
3752 /* """"""""""""""""""""""""""" */
3753 p = name;
3754 if (!isalpha(*p))
3755 fatal_internal("A context name must start with a letter: %s.", name);
3757 p++;
3758 while (*p)
3760 if (!isalnum(*p) && *p != '_')
3761 fatal_internal("A context name must only contain letters, "
3762 "numbers or '_': %s.",
3763 name);
3764 p++;
3767 ctx->name = xstrdup(name);
3768 ctx->opt_list = ll_new(); /* List of options legit in this context. */
3769 ctx->incomp_list = ll_new(); /* List of incompatible options strings. */
3770 ctx->par_bst = NULL;
3771 ctx->data = NULL;
3772 ctx->action = NULL;
3774 /* The first created context is the main one. */
3775 /* """""""""""""""""""""""""""""""""""""""""" */
3776 if (contexts_bst == NULL)
3778 main_ctx = ctx;
3780 cur_state->ctx_name = ctx->name;
3783 if (init_opts(opts_specs, ctx) == 0)
3784 exit(EXIT_FAILURE);
3785 if (bst_find(ctx, &contexts_bst, ctx_compare) != NULL)
3786 fatal_internal("The context %s already exists.", name);
3787 else
3788 bst_search(ctx, &contexts_bst, ctx_compare);
3791 /* ==================================================== */
3792 /* Display a usage screen limited to a specific context */
3793 /* IN: the context name. */
3794 /* IN: what to do after (continue or exit the program) */
3795 /* possible values: continue_after, exit_after. */
3796 /* ==================================================== */
3797 void
3798 ctxopt_ctx_disp_usage(char * ctx_name, usage_behaviour action)
3800 ctx_t * ctx;
3801 ll_t * list;
3803 int has_optional = 0;
3804 int has_ellipsis = 0;
3805 int has_rule = 0;
3806 int has_generic_arg = 0;
3807 int has_ctx_change = 0;
3808 int has_early_eval = 0;
3810 ctx = locate_ctx(ctx_name);
3811 if (ctx == NULL)
3812 fatal_internal("Unknown context %s.", ctx_name);
3814 if (cur_state->ctx_par_name == NULL)
3815 printf("\nSynopsis:\n%s \\\n", cur_state->prog_name);
3816 else
3817 printf("\nSynopsis for the context introduced by %s:\n",
3818 cur_state->ctx_par_name);
3820 list = ctx->opt_list;
3821 print_options(list, &has_optional, &has_ellipsis, &has_rule, &has_generic_arg,
3822 &has_ctx_change, &has_early_eval);
3824 print_explanations(has_early_eval, has_ctx_change, has_generic_arg,
3825 has_optional, has_ellipsis, has_rule);
3827 if (action == exit_after)
3828 exit(EXIT_FAILURE);
3831 /* =================================================== */
3832 /* Display a full usage screen about all contexts. */
3833 /* IN: what to do after (continue or exit the program) */
3834 /* possible values: continue_after, exit_after. */
3835 /* =================================================== */
3836 void
3837 ctxopt_disp_usage(usage_behaviour action)
3839 ll_t * list;
3840 int has_optional = 0;
3841 int has_ellipsis = 0;
3842 int has_rule = 0;
3843 int has_generic_arg = 0;
3844 int has_ctx_change = 0;
3845 int has_early_eval = 0;
3847 if (main_ctx == NULL)
3848 fatal_internal("At least one context must have been created.");
3850 /* Usage for the first context. */
3851 /* """""""""""""""""""""""""""" */
3852 printf("\nAllowed options in the default context:\n");
3853 list = main_ctx->opt_list;
3854 print_options(list, &has_optional, &has_ellipsis, &has_rule, &has_generic_arg,
3855 &has_ctx_change, &has_early_eval);
3857 /* Usage for the other contexts. */
3858 /* """"""""""""""""""""""""""""" */
3859 bst_walk(contexts_bst, bst_print_ctx_cb);
3861 /* Contextual syntactic explanations. */
3862 /* """""""""""""""""""""""""""""""""" */
3863 print_explanations(has_early_eval, has_ctx_change, has_generic_arg,
3864 has_optional, has_ellipsis, has_rule);
3866 if (action == exit_after)
3867 exit(EXIT_FAILURE);
3870 /* *********************************** */
3871 /* Built-in constraint check functions */
3872 /* *********************************** */
3874 /* ============================================================= */
3875 /* This constraint checks if each arguments respects a format as */
3876 /* defined for the scanf function. */
3877 /* return 1 if yes and 0 if no. */
3878 /* ============================================================= */
3880 ctxopt_format_constraint(int nb_args, char ** args, char * value, char * par)
3882 int rc = 0;
3884 char x[256];
3885 char y;
3886 char * format;
3888 if (nb_args != 1)
3889 fatal_internal("Format constraint, invalid number of parameters.");
3891 if (strlen(value) > 255)
3892 value[255] = '\0';
3894 format = xstrdup(args[0]);
3895 format = strappend(format, "%c", NULL);
3897 rc = sscanf(value, format, x, &y);
3898 if (rc != 1)
3899 fprintf(stderr,
3900 "The argument %s of %s does not respect the imposed format %s.",
3901 value, par, args[0]);
3903 free(format);
3905 return rc == 1;
3908 /* ================================================================== */
3909 /* This constraint checks if each arguments of the option instance is */
3910 /* between a minimum and a maximum (inclusive). */
3911 /* return 1 if yes and 0 if no. */
3912 /* ================================================================== */
3914 ctxopt_re_constraint(int nb_args, char ** args, char * value, char * par)
3916 regex_t re;
3918 if (nb_args != 1)
3919 fatal_internal(
3920 "Regular expression constraint, invalid number of parameters.");
3922 if (regcomp(&re, args[0], REG_EXTENDED) != 0)
3923 fatal_internal("Invalid regular expression %s.", args[0]);
3925 if (regexec(&re, value, (size_t)0, NULL, 0) != 0)
3927 fprintf(stderr,
3928 "The argument %s of %s doesn't match the constraining "
3929 "regular expression %s.",
3930 value, par, args[0]);
3931 return 0;
3934 regfree(&re);
3936 return 1;
3939 /* ================================================================== */
3940 /* This constraint checks if each arguments of the option instance is */
3941 /* between a minimum and a maximum (inclusive). */
3942 /* return 1 if yes and 0 if no. */
3943 /* ================================================================== */
3945 ctxopt_range_constraint(int nb_args, char ** args, char * value, char * par)
3947 long min, max;
3948 char c;
3949 char * ptr;
3950 int n;
3951 long v;
3952 int min_only = 0;
3953 int max_only = 0;
3955 if (nb_args != 2)
3956 fatal_internal("Range constraint, invalid number of parameters.");
3958 if (strcmp(args[0], ".") == 0)
3959 max_only = 1;
3960 else
3961 n = sscanf(args[0], "%ld%c", &min, &c);
3963 if (!max_only && n != 1)
3964 fatal_internal("Range constraint, min: invalid parameters.");
3966 if (strcmp(args[1], ".") == 0)
3967 min_only = 1;
3968 else
3969 n = sscanf(args[1], "%ld%c", &max, &c);
3971 if (!min_only && n != 1)
3972 fatal_internal("Range constraint, max: invalid parameters.");
3974 if (min_only && max_only)
3975 fatal_internal("Range constraint, invalid parameters.");
3977 errno = 0;
3978 v = strtol(value, &ptr, 10);
3979 if (errno || ptr == value)
3980 return 0;
3982 if (min_only)
3984 if (v < min)
3986 fprintf(stderr,
3987 "The argument %ld of %s is not greater than or equal to %ld.", v,
3988 par, min);
3989 return 0;
3991 else
3992 return 1;
3994 else if (max_only)
3996 if (v > max)
3998 fprintf(stderr,
3999 "The argument %ld of %s is not less than or equal to %ld.", v,
4000 par, max);
4001 return 0;
4003 else
4004 return 1;
4006 else if (v < min || v > max)
4008 fprintf(stderr, "The argument %ld of %s is not between %ld and %ld.", v,
4009 par, min, max);
4010 return 0;
4013 return 1; /* check passed */
4016 /* =============================================================== */
4017 /* This function provides a way to set the behaviour of a context. */
4018 /* =============================================================== */
4019 void
4020 ctxopt_add_global_settings(settings s, ...)
4022 va_list(args);
4023 va_start(args, s);
4025 switch (s)
4027 case error_functions:
4029 typedef void fn(errors e, state_t * state);
4031 void (*function)(errors e, state_t * state);
4033 errors e;
4034 e = va_arg(args, errors);
4035 function = va_arg(args, fn *);
4036 err_functions[e] = function;
4037 break;
4040 default:
4041 break;
4043 va_end(args);
4046 /* ================================================================ */
4047 /* This function provides a way to set the behaviour of an option. */
4048 /* It can take a variable number of arguments according to its */
4049 /* first argument: */
4050 /* - parameter: */
4051 /* o a string containing an option name and all its possible */
4052 /* parameters separates by spaces, tabs or commas (char *) */
4053 /* (e.g: "help -h -help"). */
4054 /* - actions: */
4055 /* o a string containing an option name. */
4056 /* o a pointer to a function which will be called at evaluation */
4057 /* time. */
4058 /* - constraints: */
4059 /* o a string containing an option name. */
4060 /* o a pointer to a function to check if an argument is valid. */
4061 /* o a strings containing the arguments to this function. */
4062 /* ================================================================ */
4063 void
4064 ctxopt_add_opt_settings(settings s, ...)
4066 opt_t * opt;
4067 void * ptr = NULL;
4069 va_list(args);
4070 va_start(args, s);
4072 switch (s)
4074 /* This part associates some command line parameters to an option. */
4075 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
4076 case parameters:
4078 char * opt_name;
4079 char * params;
4081 /* The second argument must be a string containing: */
4082 /* - The name of an existing option. */
4083 /* - a list of parameters with a leading dash (-). */
4084 /* """""""""""""""""""""""""""""""""""""""""""""""" */
4085 ptr = va_arg(args, char *);
4086 opt_name = ptr;
4088 if (opt_name != NULL)
4090 if ((opt = locate_opt(opt_name)) != NULL)
4092 ptr = va_arg(args, char *);
4093 params = ptr;
4095 if (!opt_set_parms(opt_name, params))
4096 fatal_internal(
4097 "Duplicated parameters or bad settings for the option %s.",
4098 params);
4100 else
4101 fatal_internal("Unknown option %s.", opt_name);
4103 else
4104 fatal_internal(
4105 "ctxopt_opt_add_settings: parameters: not enough arguments.");
4107 /* Here opt is a known option. */
4108 /* """"""""""""""""""""""""""" */
4109 if (opt->params != NULL)
4110 fatal_internal("Parameters are already set for %s.", opt_name);
4111 else
4113 size_t n;
4114 size_t l = strlen(params);
4116 opt->params = xstrdup(params);
4117 while ((n = strcspn(opt->params, " \t")) < l)
4118 opt->params[n] = '|';
4121 break;
4124 /* This part associates a callback function to an option. */
4125 /* This function will be called when an instance of an option */
4126 /* is evaluated. */
4127 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
4128 case actions:
4130 void * data;
4131 void (*function)();
4132 int nb_data = 0;
4134 /* The second argument must be the name of an existing option. */
4135 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
4136 ptr = va_arg(args, char *);
4138 if ((opt = locate_opt(ptr)) != NULL)
4140 typedef void fn(char *, char *, char *, int, char **, int, void *, int,
4141 void **);
4143 /* The third argument must be the callback function. */
4144 /* """"""""""""""""""""""""""""""""""""""""""""""""" */
4145 function = va_arg(args, fn *);
4146 opt->action = function;
4148 /* The fourth argument must be a pointer to an user's defined */
4149 /* variable or structure that the previous function can manage. */
4150 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
4151 while ((data = va_arg(args, void *)) != NULL)
4153 nb_data++;
4154 opt->data = xrealloc(opt->data, nb_data * sizeof(void *));
4155 opt->data[nb_data - 1] = data;
4157 opt->nb_data = nb_data;
4159 else
4160 fatal_internal("Unknown option %s.", ptr);
4161 break;
4164 /* This part associates a list of functions to control some */
4165 /* characteristics of the arguments of an option. */
4166 /* Each function will be called in order and must return 1 */
4167 /* to validate the arguments. */
4168 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""" */
4169 case constraints:
4171 char * value;
4172 constraint_t * cstr;
4173 int (*function)();
4175 /* The second argument must be a string. */
4176 /* """"""""""""""""""""""""""""""""""""" */
4177 ptr = va_arg(args, char *);
4179 if ((opt = locate_opt(ptr)) != NULL)
4181 typedef int fn(int, char **, char *);
4183 /* The third argument must be a function. */
4184 /* """""""""""""""""""""""""""""""""""""" */
4185 function = va_arg(args, fn *);
4187 cstr = xmalloc(sizeof(constraint_t));
4188 cstr->constraint = function;
4190 /* The fourth argument must be a string containing the argument of */
4191 /* The previous function separated by spaces or tabs. */
4192 /* Theses arguments will be passed to the previous function */
4193 /* max: 32 argument! */
4194 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
4195 value = xstrdup(va_arg(args, char *));
4197 cstr->to_free = value;
4198 cstr->args = xcalloc(sizeof(char *), 32);
4199 cstr->nb_args = str2argv(value, cstr->args, 32);
4200 ll_append(opt->constraints_list, cstr);
4202 else
4203 fatal_internal("Unknown option %s.", ptr);
4204 break;
4207 default:
4208 break;
4210 va_end(args);
4213 /* =============================================================== */
4214 /* This function provides a way to set the behaviour of a context. */
4215 /* =============================================================== */
4216 void
4217 ctxopt_add_ctx_settings(settings s, ...)
4219 ctx_t * ctx;
4221 va_list(args);
4222 va_start(args, s);
4224 switch (s)
4226 /* Add a set of mutually incompatible options in a context. */
4227 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""" */
4228 case incompatibilities:
4230 void * ptr;
4231 ll_t * list;
4232 size_t n;
4233 char * str;
4235 ptr = va_arg(args, char *);
4236 if ((ctx = locate_ctx(ptr)) != NULL)
4238 ptr = va_arg(args, char *);
4239 list = ctx->incomp_list;
4241 str = xstrdup(ptr);
4242 ltrim(str, " \t");
4243 rtrim(str, " \t", 0);
4245 n = strcspn(str, " \t");
4246 if (n > 0 && n < strlen(str))
4247 ll_append(list, str);
4248 else
4249 fatal_internal(
4250 "Not enough incompatible options in the string: \"%s\".", str);
4252 else
4253 fatal_internal("Unknown context %s.", ptr);
4254 break;
4257 /* Add functions which will be called when */
4258 /* entering and exiting a context. */
4259 /* """"""""""""""""""""""""""""""""""""""" */
4260 case actions:
4262 void * ptr;
4263 void * data;
4264 int (*function)();
4265 int nb_data = 0;
4267 ptr = va_arg(args, char *);
4268 if ((ctx = locate_ctx(ptr)) != NULL)
4270 typedef int fn(char *, direction, char *, int, void **);
4272 function = va_arg(args, fn *);
4273 ctx->action = function;
4275 while ((data = va_arg(args, void *)) != NULL)
4277 nb_data++;
4278 ctx->data = xrealloc(ctx->data, nb_data * sizeof(void *));
4279 ctx->data[nb_data - 1] = data;
4281 ctx->nb_data = nb_data;
4283 else
4284 fatal_internal("Unknown context %s.", ptr);
4285 break;
4288 default:
4289 break;
4291 va_end(args);