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 /* ################################################################### */
13 #include <sys/types.h>
19 /* ************************ */
20 /* Static global variables. */
21 /* ************************ */
23 static void * contexts_bst
;
24 static void * options_bst
;
30 /* ************************** */
31 /* Fatal messages prototypes. */
32 /* ************************** */
34 static void (**err_functions
)(errors e
, state_t
* state
);
37 fatal_internal(const char * format
, ...);
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 /* ************************************ */
56 xcalloc(size_t num
, size_t size
);
59 xrealloc(void * ptr
, size_t size
);
62 xstrdup(const char * p
);
65 xstrndup(const char * str
, size_t len
);
67 /* ********************** */
68 /* BST static prototypes. */
69 /* ********************** */
71 typedef struct bst_s bst_t
;
81 #if 0 /* Unused yet */
83 bst_delete(const void * vkey
, void ** vrootp
,
84 int (*compar
)(const void *, const void *));
88 bst_destroy(void * vrootp
, void (*clean
)(void *));
91 bst_find(const void * vkey
, void * const * vrootp
,
92 int (*compar
)(const void *, const void *));
95 bst_search(void * vkey
, void ** vrootp
,
96 int (*compar
)(const void *, const void *));
99 bst_walk_recurse(const bst_t
* root
,
100 void (*action
)(const void *, walk_order_e
, int), int level
);
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
;
113 ll_append(ll_t
* const list
, void * const data
);
116 ll_prepend(ll_t
* const list
, void * const data
);
119 ll_insert_after(ll_t
* const list
, ll_node_t
* node
, void * const data
);
122 ll_insert_before(ll_t
* const list
, ll_node_t
* node
, void * const data
);
125 ll_delete(ll_t
* const list
, ll_node_t
* node
);
127 #if 0 /* Unused yet */
129 ll_find(ll_t
* const, void * const, int (*)(const void *, const void *));
133 ll_init(ll_t
* list
);
142 ll_free(ll_t
* const list
, void (*)(void *));
145 ll_destroy(ll_t
* const list
, void (*)(void *));
148 ll_strarray(ll_t
* list
, ll_node_t
* start_node
, int * count
, char *** array
);
150 /* ************************** */
151 /* Various static prototypes. */
152 /* ************************** */
155 ltrim(char * str
, const char * trim_str
);
158 rtrim(char * str
, const char * trim_str
, size_t min
);
161 strchrcount(char * str
, char c
);
164 strpref(char * s1
, char * s2
);
167 stricmp(const char * s1
, const char * s2
);
170 xstrtok_r(char * str
, const char * delim
, char ** end
);
173 eval_yes(char * value
, int * invalid
);
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
;
192 strtoken(char * s
, char * token
, size_t tok_len
, char * pattern
, int * pos
);
195 ctx_compare(const void * c1
, const void * c2
);
201 ctx_inst_free(void * ci
);
204 opt_inst_free(void * oi
);
207 seen_opt_compare(const void * so1
, const void * so2
);
210 incomp_bst_free(void * b
);
213 seen_opt_free(void * seen_opt
);
216 opt_compare(const void * o1
, const void * o2
);
222 par_compare(const void * a1
, const void * a2
);
228 constraint_free(void * cstr
);
231 locate_ctx(char * name
);
234 locate_opt(char * name
);
237 locate_par(char * name
, ctx_t
* ctx
);
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
);
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
);
247 bst_seen_opt_cb(const void * node
, walk_order_e kind
, int level
);
250 bst_seen_opt_seen_cb(const void * node
, walk_order_e kind
, int level
);
253 bst_print_ctx_cb(const void * node
, walk_order_e kind
, int level
);
256 bst_check_opt_cb(const void * node
, walk_order_e kind
, int level
);
259 bst_match_par_cb(const void * node
, walk_order_e kind
, int level
);
262 match_prefix_cb(const void * node
, walk_order_e kind
, int level
);
265 has_unseen_mandatory_opt(ctx_inst_t
* ctx_inst
, char ** missing
);
268 opt_parse(char * s
, opt_t
** opt
);
271 init_opts(char * spec
, ctx_t
* ctx
);
274 ctxopt_build_cmdline_list(int nb_words
, char ** words
);
277 opt_set_parms(char * opt_name
, char * par_str
);
280 new_ctx_inst(ctx_t
* ctx
, ctx_inst_t
* prev_ctx_inst
);
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. */
293 /* format : printf like format */
294 /* ... : remaining arguments interpreted using the format argument */
295 /* ================================================================== */
297 fatal_internal(const char * format
, ...)
301 fprintf(stderr
, "CTXOPT: ");
303 va_start(args
, format
);
304 vfprintf(stderr
, format
, args
);
305 fprintf(stderr
, "\n");
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. */
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 */
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 /* ====================================================================== */
334 fatal(errors e
, char * errmsg
)
336 if (err_functions
[e
] != NULL
)
337 err_functions
[e
](e
, cur_state
);
346 if (cur_state
->ctx_par_name
!= NULL
)
348 "the mandatory parameter(s) %s are missing in the context "
349 "introduced by %s.\n",
350 errmsg
, cur_state
->ctx_par_name
);
353 "The mandatory parameter(s) %s are missing "
354 "in the main context.\n",
362 "The parameter %s takes no arguments "
363 "or has too many arguments.\n",
364 cur_state
->cur_opt_par_name
);
368 if (cur_state
->pre_opt_par_name
!= NULL
)
369 fprintf(stderr
, "%s requires argument(s).\n",
370 cur_state
->pre_opt_par_name
);
372 fprintf(stderr
, "%s requires argument(s).\n",
373 cur_state
->cur_opt_par_name
);
377 if (cur_state
->pre_opt_par_name
!= NULL
)
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
);
384 "The parameter %s can only appear once "
385 "in the main context.\n",
386 cur_state
->cur_opt_params
);
390 fprintf(stderr
, "Unknown parameter %s.\n", cur_state
->cur_opt_par_name
);
394 fprintf(stderr
, "The parameter %s is incompatible with %s.\n",
395 cur_state
->cur_opt_par_name
, errmsg
);
399 if (cur_state
->ctx_par_name
)
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
);
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
);
413 if (cur_state
->ctx_par_name
)
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
);
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
);
427 if (cur_state
->ctx_par_name
)
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
);
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
);
441 fprintf(stderr
, "The parameter %s must have exactly %d arguments.\n",
442 cur_state
->cur_opt_par_name
, cur_state
->opt_args_count
);
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
);
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
);
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 /* ================== */
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
);
487 /* ================== */
488 /* Customized calloc. */
489 /* ================== */
491 xcalloc(size_t n
, size_t size
)
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
);
505 /* =================== */
506 /* Customized realloc. */
507 /* =================== */
509 xrealloc(void * p
, size_t size
)
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
);
521 /* ==================================== */
522 /* strdup implementation using xmalloc. */
523 /* ==================================== */
525 xstrdup(const char * p
)
529 allocated
= xmalloc(strlen(p
) + 1);
530 strcpy(allocated
, p
);
535 /* =================================================== */
536 /* strndup implementation using xmalloc. */
537 /* This version guarantees that there is a final '\0'. */
538 /* =================================================== */
540 xstrndup(const char * str
, size_t len
)
544 p
= memchr(str
, '\0', len
);
549 p
= xmalloc(len
+ 1);
556 /* *************************** */
557 /* Linked list implementation. */
558 /* *************************** */
560 /* Linked list node structure. */
561 /* """"""""""""""""""""""""""" */
565 struct ll_node_s
* next
;
566 struct ll_node_s
* prev
;
569 /* Linked List structure. */
570 /* """""""""""""""""""""" */
578 /* ========================= */
579 /* Create a new linked list. */
580 /* ========================= */
584 ll_t
* ret
= xmalloc(sizeof(ll_t
));
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 /* =============================================== */
596 ll_free(ll_t
* const list
, void (*clean
)(void *))
601 /* Apply a custom cleaner if not NULL. */
602 /* """"""""""""""""""""""""""""""""""" */
604 clean(list
->head
->data
);
606 ll_delete(list
, list
->head
);
610 /* ==================================== */
611 /* Destroy a list and all its elements. */
612 /* ==================================== */
614 ll_destroy(ll_t
* list
, void (*clean
)(void *))
618 ll_free(list
, clean
);
623 /* ========================= */
624 /* Initialize a linked list. */
625 /* ========================= */
634 /* ===================================================== */
635 /* Allocate the space for a new node in the linked list. */
636 /* ===================================================== */
640 ll_node_t
* ret
= xmalloc(sizeof(ll_node_t
));
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 /* ==================================================================== */
650 ll_append(ll_t
* const list
, void * const data
)
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. */
661 node
->prev
= list
->tail
;
663 list
->tail
->next
= node
;
672 /* ================================================================== */
673 /* Put a new node filled with its data at the beginning of the linked */
675 /* The user is responsible for the memory management of the data. */
676 /* ================================================================== */
678 ll_prepend(ll_t
* const list
, void * const data
)
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. */
689 node
->next
= list
->head
;
691 list
->head
->prev
= node
;
700 /* ======================================================== */
701 /* Insert a new node before the specified node in the list. */
702 /* ======================================================== */
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
);
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
;
726 /* ======================================================= */
727 /* Insert a new node after the specified node in the list. */
728 /* ======================================================= */
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
);
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
;
752 /* ================================================================= */
753 /* Remove a node from a linked list */
754 /* The memory taken by the deleted node must be freed by the caller. */
755 /* ================================================================= */
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
;
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
;
778 node
->next
->prev
= node
->prev
;
779 node
->prev
->next
= node
->next
;
789 #if 0 /* Unused yet */
790 /* ======================================================================== */
791 /* Find a node in the list containing data. Return the node pointer or NULL */
793 /* A comparison function must be provided to compare a and b (strcmp like). */
794 /* ======================================================================== */
796 ll_find(ll_t
* const list
, void * const data
,
797 int (*cmpfunc
)(const void * a
, const void * b
))
801 if (NULL
== (node
= list
->head
))
806 if (0 == cmpfunc(node
->data
, data
))
808 } while (NULL
!= (node
= node
->next
));
814 /* ==================================================================== */
815 /* Allocate and fill an array of strings from a list. */
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. */
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 /* ==================================================================== */
829 ll_strarray(ll_t
* list
, ll_node_t
* start_node
, int * count
, char *** array
)
838 if (list
== NULL
|| node
== NULL
)
845 *array
= xmalloc((list
->len
+ 1) * sizeof(char *));
848 (*array
)[n
++] = (char *)(node
->data
);
854 (*array
)[*count
] = NULL
;
859 /* ******************************************************************* */
860 /* BST (search.h compatible) implementation. */
862 /* Tree search generalized from Knuth (6.2.2) Algorithm T just like */
863 /* the AT&T man page says. */
865 /* Written by reading the System V Interface Definition, not the code. */
867 /* Totally public domain. */
868 /* ******************************************************************* */
873 struct bst_s
* llink
;
874 struct bst_s
* rlink
;
877 #if 0 /* Unused yet */
878 /* =========================== */
879 /* Delete node with given key. */
880 /* =========================== */
882 bst_delete(const void * vkey
, void ** vrootp
,
883 int (*compar
)(const void *, const void *))
885 bst_t
** rootp
= (bst_t
**)vrootp
;
889 if (rootp
== NULL
|| (p
= *rootp
) == NULL
)
892 while ((cmp
= (*compar
)(vkey
, (*rootp
)->key
)) != 0)
895 rootp
= (cmp
< 0) ? &(*rootp
)->llink
/* follow llink branch */
896 : &(*rootp
)->rlink
; /* follow rlink branch */
898 return NULL
; /* key not found */
900 r
= (*rootp
)->rlink
; /* D1: */
901 if ((q
= (*rootp
)->llink
) == NULL
) /* Left NULL? */
904 { /* Right link is NULL? */
905 if (r
->llink
== NULL
)
906 { /* D2: Find successor */
911 { /* D3: Find NULL link */
912 for (q
= r
->llink
; q
->llink
!= NULL
; q
= r
->llink
)
915 q
->llink
= (*rootp
)->llink
;
916 q
->rlink
= (*rootp
)->rlink
;
920 free(*rootp
); /* D4: Free node */
921 *rootp
= q
; /* link parent to new node */
926 /* ===================================================================== */
927 /* Destroy a tree. */
928 /* The clean function pointer can be NULL, in this case the node content */
930 /* ===================================================================== */
932 bst_destroy(void * vrootp
, void (*clean
)(void *))
934 bst_t
* root
= (bst_t
*)vrootp
;
939 bst_destroy(root
->llink
, clean
);
940 bst_destroy(root
->rlink
, clean
);
943 clean((void *)root
->key
);
948 /* ========================= */
949 /* Find a node, or return 0. */
950 /* ========================= */
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
;
960 while (*rootp
!= NULL
)
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 */
972 /* ======================================= */
973 /* Find or inserts datum into search tree. */
974 /* ======================================= */
976 bst_search(void * vkey
, void ** vrootp
,
977 int (*compar
)(const void *, const void *))
980 bst_t
** rootp
= (bst_t
**)vrootp
;
985 while (*rootp
!= NULL
)
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 */
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
;
1006 /* ========================= */
1007 /* Walk the nodes of a tree. */
1008 /* ========================= */
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
);
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
);
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 /* ======================== */
1042 ltrim(char * str
, const char * trim_str
)
1044 size_t len
= strlen(str
);
1045 size_t begin
= strspn(str
, trim_str
);
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 /* ================================================= */
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]))
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 /* ================================================== */
1072 strchrcount(char * str
, char c
)
1083 /* =============================================== */
1084 /* Is the string str2 a prefix of the string str1? */
1085 /* =============================================== */
1087 strpref(char * str1
, char * str2
)
1089 while (*str1
!= '\0' && *str1
== *str2
)
1095 return *str2
== '\0';
1098 /* ========================== */
1099 /* Like strcmp ignoring case. */
1100 /* ========================== */
1102 stricmp(const char * s1
, const char * s2
)
1104 while (tolower((unsigned char)*s1
) == tolower((unsigned char)*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 */
1120 /* The first one must have been dynamically allocated and is mandatory */
1122 /* Returns a new allocated string containing the concatenation of all */
1123 /* the arguments. It is the caller's responsibility to free the resulting */
1125 /* ======================================================================== */
1127 strappend(char * str
, ...)
1133 l
= 1 + strlen(str
);
1134 va_start(args
, str
);
1136 s
= va_arg(args
, char *);
1141 s
= va_arg(args
, char *);
1146 str
= xrealloc(str
, l
);
1148 va_start(args
, str
);
1149 s
= va_arg(args
, char *);
1154 s
= va_arg(args
, char *);
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 */
1166 /* (Declaration that it's public domain): */
1167 /* http://groups.google.com/group/comp.lang.c/msg/7c7b39328fefab9c */
1169 /* Also, fixed by Fletcher T. Penney --- added the "return NULL" when */
1171 /* ====================================================================== */
1173 xstrtok_r(char * str
, const char * delim
, char ** end
)
1183 str
+= strspn(str
, delim
);
1190 str
+= strcspn(str
, delim
);
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 /* ===================================================================== */
1208 get_word(char * str
, char * buf
, size_t len
)
1214 while (*s
&& isspace(*s
))
1217 /* Set the new string start. */
1218 /* """"""""""""""""""""""""" */
1223 while (*s
&& !isspace(*s
) && s
- str
< len
)
1226 strncpy(buf
, str
, s
- str
);
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 /* ==================================================================== */
1239 eval_yes(char * value
, int * invalid
)
1243 if (strcmp(value
, "1") == 0 || stricmp(value
, "yes") == 0)
1245 else if (strcmp(value
, "0") != 0 && stricmp(value
, "no") != 0)
1251 /* =========================================================== */
1252 /* Fill an array of strings from the words composing a string. */
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 /* =========================================================== */
1260 str2argv(char * str
, char ** args
, int max
)
1269 while (*str
== ' ' || *str
== '\t')
1275 args
[nb_args
] = str
;
1278 while (*str
&& (*str
!= ' ') && (*str
!= '\t'))
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 /* """"""""""""""""""""""""""""""""""""""""""" */
1295 int stop_if_non_option
;
1296 int allow_abbreviations
;
1299 /* Context structure. */
1300 /* """""""""""""""""" */
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
,
1314 /* https://textik.com/#488ce3649b6c60f5 */
1316 /* +--------------+ */
1317 /* |first_ctx_inst| */
1318 /* +---+----------+ */
1320 /* +--v-----+ +--------+ +--------+ +-----+ */
1321 /* +---+-->ctx_inst+------>opt_inst+----->opt_inst+------> ... | */
1322 /* | | +-+------+ +----+---+ +----+---+ +-----+ */
1324 /* | | +-v------+ | | */
1325 /* | +--+ctx_inst<-----------+ | */
1326 /* | +-+------+ | */
1328 /* | +-v------+ | */
1329 /* +------+ctx_inst<--------------------------+ */
1336 /* Option structure. */
1337 /* """"""""""""""""" */
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 *
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 *
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 /* """"""""""""""""""""""""""" */
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 /* """""""""""""""""""""""""" */
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 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""" */
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 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
1430 char * name
; /* Parameter name (with the leading -). */
1431 opt_t
* opt
; /* Attached option. */
1434 /* Constraint structure. */
1435 /* """"""""""""""""""""" */
1438 int (*constraint
)(int nb_args
, char ** args
, char * value
, char * parameter
);
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. */
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. */
1466 /* Returns: a pointer to the first unread character or */
1467 /* to he terminating \0. */
1468 /* ======================================================= */
1470 strtoken(char * s
, char * token
, size_t tok_len
, char * pattern
, int * pos
)
1472 char * full_pattern
;
1478 n
= snprintf(len
, 3, "%zu", tok_len
);
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
);
1499 /* ****************************************** */
1500 /* Various comparison and deletion functions. */
1501 /* ****************************************** */
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 /* =========================== */
1520 ll_destroy(ctx
->opt_list
, NULL
);
1521 ll_destroy(ctx
->incomp_list
, free
);
1522 bst_destroy(ctx
->par_bst
, par_free
);
1527 /* ============================= */
1528 /* Free a ctx_inst_list element. */
1529 /* ============================= */
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
);
1543 /* ============================= */
1544 /* Free a opt_inst_list element. */
1545 /* ============================= */
1547 opt_inst_free(void * oi
)
1549 opt_inst_t
* opt_inst
= oi
;
1551 ll_destroy(opt_inst
->values_list
, NULL
);
1556 /* ================================== */
1557 /* Compare two seen_opt_bst elements. */
1558 /* ================================== */
1560 seen_opt_compare(const void * so1
, const void * so2
)
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 /* ============================ */
1574 seen_opt_free(void * so
)
1576 seen_opt_t
* seen_opt
= so
;
1578 free(seen_opt
->par
);
1583 /* =========================== */
1584 /* Free an incomp_bst element. */
1585 /* =========================== */
1587 incomp_bst_free(void * b
)
1591 bst_destroy(bst
, NULL
);
1594 /* ================================= */
1595 /* Compare two options_bst elements. */
1596 /* ================================= */
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 /* ============================= */
1612 free(opt
->next_ctx
);
1617 ll_destroy(opt
->ctx_list
, NULL
);
1618 ll_destroy(opt
->constraints_list
, constraint_free
);
1623 /* ============================= */
1624 /* Compare two par_bst elements. */
1625 /* ============================= */
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 /* ======================= */
1645 /* ================================ */
1646 /* Free a constraints_list element. */
1647 /* ================================ */
1649 constraint_free(void * c
)
1651 constraint_t
* cstr
= c
;
1654 free(cstr
->to_free
);
1659 /* ******************************************************************** */
1660 /* Helper functions to locate contexts, options and parameters in a BST */
1661 /* by their names. */
1662 /* ******************************************************************** */
1665 locate_ctx(char * name
)
1672 if ((node
= bst_find(&ctx
, &contexts_bst
, ctx_compare
)) == NULL
)
1679 locate_opt(char * name
)
1686 if ((node
= bst_find(&opt
, &options_bst
, opt_compare
)) == NULL
)
1693 locate_par(char * name
, ctx_t
* ctx
)
1697 void * bst
= ctx
->par_bst
;
1701 if ((node
= bst_find(&par
, &bst
, par_compare
)) == NULL
)
1707 /* =================================================================== */
1708 /* Utility function to format and print the options present in a list. */
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 */
1714 /* =================================================================== */
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
;
1725 line
= xstrdup(" ");
1727 while (node
!= NULL
)
1729 option
= xstrdup("");
1734 option
= strappend(option
, "[", NULL
);
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;
1754 if (opt
->opt_count_oper
!= '\0')
1758 o
[0] = opt
->opt_count_oper
;
1760 snprintf(m
, 3, "%u", opt
->opt_count_mark
);
1761 option
= strappend(option
, "...", o
, m
, NULL
);
1765 option
= strappend(option
, "...", NULL
);
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
);
1783 option
= strappend(option
, opt
->arg
, NULL
);
1785 if (opt
->multiple_args
)
1787 if (opt
->opt_args_count_oper
!= '\0')
1791 o
[0] = opt
->opt_args_count_oper
;
1793 snprintf(m
, 3, "%u", opt
->opt_args_count_mark
);
1794 option
= strappend(option
, "...", o
, m
, NULL
);
1798 option
= strappend(option
, "...", NULL
);
1802 if (opt
->optional_args
)
1803 option
= strappend(option
, "]", NULL
);
1806 option
= strappend(option
, "]", NULL
);
1808 if (strlen(line
) + 1 + strlen(option
) < 80)
1809 line
= strappend(line
, option
, " ", NULL
);
1812 printf("%s\n", line
);
1814 line
= strappend(line
, option
, " ", NULL
);
1822 printf("%s\n", line
);
1827 /* ==================================================== */
1828 /* Explain the special syntactic symbols present in the */
1829 /* generated usage messages. */
1830 /* ==================================================== */
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 "
1845 printf("* : the parameters for this option will be "
1846 "evaluated first.\n");
1849 "> : The context after this symbol will become the next "
1851 if (has_generic_arg
)
1852 printf("#tag : argument tag giving a clue to its meaning.\n");
1855 "[...] : the object between square brackets is optional.\n");
1857 printf("... : several occurrences of the previous object "
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 /* ************************************************************ */
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)
1880 user_string
= strappend(user_string
, seen_opt
->opt
->params
, " ", NULL
);
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)
1894 user_object
= seen_opt
->par
;
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
;
1906 int has_optional
= 0;
1907 int has_ellipsis
= 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
);
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
);
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
);
1955 str
[strlen(str
) - 1] = '\0';
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
))
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 */
1980 /* IN word : the word to be checked. */
1981 /* IN ctx : the context in which the flag indexed by the word is to be */
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. */
1987 /* The returned pointer must be freed by the caller. */
1988 /* ====================================================================== */
1990 look_for_valid_prefix_in_word(char * word
, ctx_t
* ctx
, int * pos
, opt_t
** opt
)
1995 par_t tmp_par
= { 0 };
2001 new = xstrdup(word
);
2007 } while ((par
= locate_par(tmp_par
.name
, ctx
)) == NULL
&& len
> 2);
2026 /* ============================================================= */
2027 /* If par_name is an unique abbreviation of an exiting parameter */
2028 /* in the context ctx, then return this parameter. */
2029 /* ============================================================= */
2031 abbrev_expand(char * par_name
, ctx_t
* ctx
)
2033 user_object
= par_name
;
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. */
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 */
2057 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2058 s
= first_s
= strtok(user_string
, " "); /* first_s holds a copy of *
2059 | the first word. */
2062 par
= locate_par(s
, ctx
);
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
);
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
);
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
);
2092 /* ================================================================ */
2093 /* Terminate the program if mandatory options required by a context */
2094 /* are not present. */
2095 /* ================================================================ */
2097 check_for_missing_mandatory_opt(ctx_inst_t
* ctx_inst
, char * opt_par
)
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 /* ====================================================== */
2110 has_unseen_mandatory_opt(ctx_inst_t
* ctx_inst
, char ** missing
)
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 /* ========================================================================= */
2130 check_for_occurrences_issues(ctx_inst_t
* ctx_inst
)
2132 ctx_t
* ctx
= ctx_inst
->ctx
;
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
)
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
)
2157 if (opt
->occurrences
> 0 && opt
->opt_count_mark
!= opt
->occurrences
)
2158 fatal(CTXOPTCTEOPT
, NULL
);
2162 if (opt
->occurrences
> 0 && opt
->opt_count_mark
<= opt
->occurrences
)
2163 fatal(CTXOPTCTLOPT
, NULL
);
2167 if (opt
->occurrences
> 0 && opt
->opt_count_mark
>= opt
->occurrences
)
2168 fatal(CTXOPTCTGOPT
, NULL
);
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
)
2195 if (nb_values
> 0 && opt
->opt_args_count_mark
!= nb_values
)
2196 fatal(CTXOPTCTEARG
, NULL
);
2200 if (nb_values
> 0 && opt
->opt_args_count_mark
<= nb_values
)
2201 fatal(CTXOPTCTLARG
, NULL
);
2205 if (nb_values
> 0 && opt
->opt_args_count_mark
>= nb_values
)
2206 fatal(CTXOPTCTGARG
, NULL
);
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: */
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... [#...]" */
2226 /* Where [ ] encloses an optional part, # means: has parameters and ... */
2227 /* means that there can be more than one occurrence of the previous thing. */
2229 /* opt_name can be followed by a 'new context' change prefixed with the */
2230 /* symbol >, as in opt1>c2 by eg. */
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. */
2235 /* In case of successful parsing, an new option is allocated and its */
2236 /* pointer returned. */
2237 /* ======================================================================== */
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;
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;
2267 memset(opt_arg
, '\0', 33);
2269 /* Strip the leading blanks. */
2270 /* """"""""""""""""""""""""" */
2274 if (*s
== '[') /* Start of an optional option. */
2279 s
= strtoken(s
, token
, sizeof(token
) - 1, "[^] \n\t.]", &pos
);
2281 return -1; /* Empty string. */
2283 /* Early EOS, only return success if the option is mandatory. */
2284 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2286 if (opt_optional
== 1)
2287 return -(s
- s_orig
- 1);
2289 /* Validate the option name */
2290 /* ALPHA+(ALPHANUM|_)* */
2291 /* """""""""""""""""""""""" */
2293 if (!isalpha(*p
) && *p
!= '*')
2294 return -(s
- s_orig
- 1); /* opt_name must start with a letter. */
2302 if (!isalnum(*p
) && *p
!= '_' && *p
!= '>')
2303 return -(s
- s_orig
- 1); /* opt_name must contain a letter, *
2304 * a number or a _ */
2309 opt_name
= xstrdup(token
+ 1); /* Ignore the first '*' in token. */
2311 opt_name
= xstrdup(token
);
2322 /* Check if it can appear multiple times by looking for the dots. */
2323 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2324 p
= strtoken(s
, token
, 3, "[.]", &pos
);
2327 if (strcmp(token
, "...") == 0)
2331 if (*s
== '<' || *s
== '=' || *s
== '>')
2336 n
= sscanf(s
+ 1, "%u%n", &value
, &offset
);
2339 opt_count_matter
= 1;
2340 opt_count_oper
= *s
;
2341 opt_count_mark
= value
;
2349 return -(s
- s_orig
- 1);
2353 /* A blank separates the option name and the argument tag. */
2354 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""" */
2366 n
= sscanf(s
, "[%32[^] .\t]%n%3[.]", opt_arg
, &pos
, dots
);
2367 if (pos
> 1 && *opt_arg
== '#') /* [# has been read. */
2370 opt_optional_args
= 1;
2372 opt_multiple_args
= 1; /* There were dots. */
2374 s
+= pos
+ !!(n
== 2) * 3; /* Skips the dots. */
2376 if (*s
== '<' || *s
== '=' || *s
== '>')
2381 n
= sscanf(s
+ 1, "%u%n", &value
, &offset
);
2384 opt_args_count_matter
= 1;
2385 opt_args_count_oper
= *s
;
2386 opt_args_count_mark
= value
;
2391 /* Optional arg tag must end with a ] */
2392 /* """""""""""""""""""""""""""""""""" */
2396 return -(s
- s_orig
- 1);
2399 s
++; /* Skip the ] */
2403 n
= sscanf(s
, "%32[^] .\t]%n%3[.]", opt_arg
, &pos
, dots
);
2404 if (pos
> 0 && *opt_arg
== '#') /* # has been read. */
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
== '>')
2417 n
= sscanf(s
+ 1, "%u%n", &value
, &offset
);
2420 opt_args_count_matter
= 1;
2421 opt_args_count_oper
= *s
;
2422 opt_args_count_mark
= value
;
2430 /* Abort on extraneous ] if the option is mandatory. */
2431 /* """"""""""""""""""""""""""""""""""""""""""""""""" */
2433 return -(s
- s_orig
- 1);
2435 s
++; /* skip the ] */
2437 /* Strip the following blanks. */
2438 /* """"""""""""""""""""""""""" */
2444 else if (opt_optional
== 0 && (!*s
|| isblank(*s
)))
2446 /* Strip the following blanks. */
2447 /* """"""""""""""""""""""""""" */
2453 else if (opt_args
== 0) /* # was not read it is possibly the start *
2454 * of another option. */
2457 return -(s
- s_orig
- 1);
2462 /* Strip the following blanks. */
2463 /* """"""""""""""""""""""""""" */
2469 if (*opt_name
== '>')
2470 fatal_internal("The option name is missing in %s.", opt_name
);
2472 count
= strchrcount(opt_name
, '>');
2475 char * tmp
= strchr(opt_name
, '>');
2476 next_ctx
= xstrdup(tmp
+ 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
;
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. */
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 */
2516 /* ==================================================================== */
2518 init_opts(char * spec
, ctx_t
* ctx
)
2520 opt_t
* opt
, *bst_opt
;
2526 if ((offset
= opt_parse(spec
, &opt
)) > 0)
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
)
2538 else if (bst_opt
->next_ctx
== NULL
&& opt
->next_ctx
!= NULL
)
2540 else if (bst_opt
->next_ctx
!= NULL
&& opt
->next_ctx
== NULL
)
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",
2554 /* The newly created opt is already present in options_bst. */
2555 /* We can remove it. */
2556 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""" */
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
);
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
);
2585 char * s
= xstrndup(spec
, -offset
);
2586 printf("%s <---\nSyntax error at or before offset %d\n", s
, -offset
);
2596 /* ===================================================== */
2597 /* ctxopt initialization function, must be called first. */
2598 /* ===================================================== */
2600 ctxopt_init(char * prog_name
, char * init_flags
)
2604 contexts_bst
= NULL
;
2610 user_string
= xmalloc(8);
2611 user_string2
= xmalloc(8);
2613 char flag
[33], fname
[31], vname
[31];
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)))
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;
2642 flags
.stop_if_non_option
= 0;
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;
2651 flags
.allow_abbreviations
= 0;
2653 fatal_internal("Invalid flag value for %s: %s.", fname
, vname
);
2656 fatal_internal("Invalid flag name: %s.", fname
);
2660 /* Update current_state. */
2661 /* """"""""""""""""""""" */
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);
2669 cur_state
->prog_name
= xstrdup(prog_name
);
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. */
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 /* ========================================================================= */
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
;
2694 par_t
* par
, tmp_par
;
2695 int rc
= 1; /* return code */
2700 /* Look if the given option is defined. */
2701 /* """""""""""""""""""""""""""""""""""" */
2702 opt
= locate_opt(opt_name
);
2704 fatal_internal("Unknown option %s.", opt_name
);
2706 /* For each context using this option. */
2707 /* """"""""""""""""""""""""""""""""""" */
2708 list
= opt
->ctx_list
;
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
);
2719 fatal_internal("Unknown context %s.", ctx_name
);
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
);
2741 fatal_internal("The parameter %s is already defined in context %s.",
2742 par_name
, ctx
->name
);
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
;
2763 lnode
= lnode
->next
;
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 /* ==================================================================== */
2778 new_ctx_inst(ctx_t
* ctx
, ctx_inst_t
* prev_ctx_inst
)
2781 opt_inst_t
* gen_opt_inst
;
2782 ctx_inst_t
* ctx_inst
;
2783 seen_opt_t
* seen_opt
;
2784 char * str
, *opt_name
;
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
;
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
;
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
)
2824 opt
->occurrences
= 0;
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
)
2836 seen_opt
= xmalloc(sizeof(seen_opt_t
));
2837 seen_opt
->opt
= opt
;
2838 seen_opt
->par
= NULL
;
2841 bst_search(seen_opt
, &(ctx_inst
->seen_opt_bst
), seen_opt_compare
);
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. */
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
)
2859 seen_opt_t tmp_seen_opt
;
2861 str
= xstrdup(node
->data
);
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 */
2872 /* """"""""""""""""""""""""""""""""""""""""""""""""""""" */
2873 tmp_seen_opt
.opt
= opt
;
2875 bst_node
= bst_find(&tmp_seen_opt
, &(ctx_inst
->seen_opt_bst
),
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
);
2886 /* Not found! That means that the option is unknown in this */
2887 /* context as all options has have a seen_opt structure in */
2889 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2890 fatal_internal("%s is not known in the context %s.", opt
->name
,
2894 fatal_internal("Unknown option %s.", opt_name
);
2896 opt_name
= strtok(NULL
, " \t");
2900 ll_append(ctx_inst
->incomp_bst_list
, bst
);
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. */
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. */
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 */
2921 /* Returns : 1 on success, 0 if a { or } is missing. */
2922 /* ====================================================================== */
2924 ctxopt_build_cmdline_list(int nb_words
, char ** words
)
2927 char * prev_word
= NULL
;
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. */
2936 /* In the following, SG is the ascii character 1d (dec 29) */
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 */
2942 /* The second pass transform the '{...}' blocks by a trailing SG */
2943 /* ({...} -> ...|) */
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 */
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
)
2958 ll_delete(cmdline_list
, node
);
2959 node
= cmdline_list
->head
;
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
]);
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. */
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));
2996 start_node
= cmdline_list
->tail
;
3000 if (str
[end
] == '{' || str
[end
] == '}')
3002 if (end
> 0 && str
[end
- 1] != '\\')
3004 ll_append(cmdline_list
, xstrndup(str
+ end
, 1));
3006 node
= cmdline_list
->tail
;
3008 while (str
[end
] == '{' || str
[end
] == '}')
3010 if (end
> start
&& str
[end
- 1] == '\\')
3013 ll_insert_before(cmdline_list
, node
, xstrndup(str
+ end
, 1));
3022 if (start_node
!= NULL
)
3023 ll_insert_after(cmdline_list
, start_node
,
3024 xstrndup(str
+ start
, end
- start
+ 1));
3026 ll_append(cmdline_list
, xstrndup(str
+ start
, end
- start
+ 1));
3027 start_node
= cmdline_list
->tail
;
3032 ll_append(cmdline_list
, xstrdup(str
));
3033 start_node
= cmdline_list
->tail
;
3039 node
= cmdline_list
->head
;
3042 while (node
!= NULL
)
3046 if (strcmp(word
, "{") == 0)
3048 ll_node_t
* old_node
= node
;
3052 ll_delete(cmdline_list
, old_node
);
3054 else if (strcmp(word
, "}") == 0)
3072 node
= cmdline_list
->head
;
3074 while (node
!= NULL
)
3078 /* Restore the original { and } characters forming the legal word {}. */
3079 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3080 while ((ptr
= strchr(word
, 0x02)) != NULL
)
3082 while ((ptr
= strchr(word
, 0x03)) != NULL
)
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
;
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. */
3101 node
->data
= xstrdup("\\-");
3104 prev_word
= node
->data
;
3108 /* Clean useless and SG at the beginning and end of list. */
3109 /* """""""""""""""""""""""""""""""""""""""""""""""""""""" */
3110 node
= cmdline_list
->head
;
3117 if (strcmp(word
, "\x1d") == 0)
3120 ll_delete(cmdline_list
, node
);
3123 node
= cmdline_list
->tail
;
3129 if (strcmp(word
, "\x1d") == 0)
3132 ll_delete(cmdline_list
, node
);
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 */
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 */
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 /* ===================================================================== */
3160 ctxopt_analyze(int nb_words
, char ** words
, int * nb_rem_args
,
3166 ctx_inst_t
* ctx_inst
;
3167 opt_inst_t
* opt_inst
;
3170 int expect_par_or_arg
= 0;
3172 ll_node_t
* cli_node
;
3174 seen_opt_t
* bst_seen_opt
;
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 /* """"""""""""""""""""""""""""""""" */
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
;
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
;
3240 /* Update current_state. */
3241 /* """"""""""""""""""""" */
3242 cur_state
->ctx_par_name
= NULL
;
3245 else if (expect_par
&& *par_name
== '-')
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
)
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
;
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 */
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. */
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
);
3299 word
= xstrdup(par_name
+ pos
);
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 */
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')
3341 "\nIt appears to be defined in the context(s):", user_string2
,
3345 fatal(CTXOPTUNKPAR
, errmsg
);
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
;
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 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
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
);
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
,
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 /* """""""""""""""""""""""""""""""""""""""""" */
3418 bst_node
= bst_find(&seen_opt
, &(ctx_inst
->seen_opt_bst
),
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
)
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 */
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
);
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
);
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;
3492 expect_par
= 1; /* Parameter doesn't accept any argument. */
3495 if (!opt
->optional_args
)
3496 expect_arg
= 1; /* Parameter has mandatory arguments. */
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 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3513 if (strcmp(n
->data
, "--") == 0 || strcmp(n
->data
, "\x1d") == 0)
3514 fatal(CTXOPTUNXARG
, NULL
);
3516 if (*(char *)(n
->data
) == '-')
3517 fatal(CTXOPTUNXARG
, NULL
);
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 *
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);
3555 ll_append(opt_inst
->values_list
, par_name
);
3559 expect_par_or_arg
= 0;
3561 if (opt
->multiple_args
)
3562 expect_par_or_arg
= 1;
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
)
3572 expect_par_or_arg
= 0;
3574 if (*par_name
!= '-')
3575 expect_arg
= 1; /* Consider this word as an argument and retry. */
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
);
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
);
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
);
3631 *rem_args
= xmalloc(sizeof(char *));
3632 (*rem_args
)[0] = NULL
;
3636 /* ==================================================== */
3637 /* Free ctxopt memory used for its internal structures. */
3638 /* ==================================================== */
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 /* ==================================================================== */
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 /* =================================================================== */
3665 evaluate_ctx_inst(ctx_inst_t
* ctx_inst
)
3667 opt_inst_t
* opt_inst
;
3670 ll_node_t
* opt_inst_node
;
3674 if (ctx_inst
== NULL
)
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
)
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
);
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
,
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
);
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
);
3729 ctx
->action(ctx
->name
, exiting
, NULL
, ctx
->nb_data
, ctx
->data
);
3733 /* ============================================================ */
3734 /* Create and initializes a new context. */
3735 /* - allocate space. */
3737 /* - initialize its option with a few of their characteristics. */
3738 /* ============================================================ */
3740 ctxopt_new_ctx(char * name
, char * opts_specs
)
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 /* """"""""""""""""""""""""""" */
3755 fatal_internal("A context name must start with a letter: %s.", name
);
3760 if (!isalnum(*p
) && *p
!= '_')
3761 fatal_internal("A context name must only contain letters, "
3762 "numbers or '_': %s.",
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
;
3774 /* The first created context is the main one. */
3775 /* """""""""""""""""""""""""""""""""""""""""" */
3776 if (contexts_bst
== NULL
)
3780 cur_state
->ctx_name
= ctx
->name
;
3783 if (init_opts(opts_specs
, ctx
) == 0)
3785 if (bst_find(ctx
, &contexts_bst
, ctx_compare
) != NULL
)
3786 fatal_internal("The context %s already exists.", name
);
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 /* ==================================================== */
3798 ctxopt_ctx_disp_usage(char * ctx_name
, usage_behaviour action
)
3803 int has_optional
= 0;
3804 int has_ellipsis
= 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
);
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
);
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
)
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 /* =================================================== */
3837 ctxopt_disp_usage(usage_behaviour action
)
3840 int has_optional
= 0;
3841 int has_ellipsis
= 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
)
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
)
3889 fatal_internal("Format constraint, invalid number of parameters.");
3891 if (strlen(value
) > 255)
3894 format
= xstrdup(args
[0]);
3895 format
= strappend(format
, "%c", NULL
);
3897 rc
= sscanf(value
, format
, x
, &y
);
3900 "The argument %s of %s does not respect the imposed format %s.",
3901 value
, par
, args
[0]);
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
)
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)
3928 "The argument %s of %s doesn't match the constraining "
3929 "regular expression %s.",
3930 value
, par
, args
[0]);
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
)
3956 fatal_internal("Range constraint, invalid number of parameters.");
3958 if (strcmp(args
[0], ".") == 0)
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)
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.");
3978 v
= strtol(value
, &ptr
, 10);
3979 if (errno
|| ptr
== value
)
3987 "The argument %ld of %s is not greater than or equal to %ld.", v
,
3999 "The argument %ld of %s is not less than or equal to %ld.", v
,
4006 else if (v
< min
|| v
> max
)
4008 fprintf(stderr
, "The argument %ld of %s is not between %ld and %ld.", v
,
4013 return 1; /* check passed */
4016 /* =============================================================== */
4017 /* This function provides a way to set the behaviour of a context. */
4018 /* =============================================================== */
4020 ctxopt_add_global_settings(settings s
, ...)
4027 case error_functions
:
4029 typedef void fn(errors e
, state_t
* state
);
4031 void (*function
)(errors e
, state_t
* state
);
4034 e
= va_arg(args
, errors
);
4035 function
= va_arg(args
, fn
*);
4036 err_functions
[e
] = function
;
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: */
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"). */
4055 /* o a string containing an option name. */
4056 /* o a pointer to a function which will be called at evaluation */
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 /* ================================================================ */
4064 ctxopt_add_opt_settings(settings s
, ...)
4074 /* This part associates some command line parameters to an option. */
4075 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
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 *);
4088 if (opt_name
!= NULL
)
4090 if ((opt
= locate_opt(opt_name
)) != NULL
)
4092 ptr
= va_arg(args
, char *);
4095 if (!opt_set_parms(opt_name
, params
))
4097 "Duplicated parameters or bad settings for the option %s.",
4101 fatal_internal("Unknown option %s.", opt_name
);
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
);
4114 size_t l
= strlen(params
);
4116 opt
->params
= xstrdup(params
);
4117 while ((n
= strcspn(opt
->params
, " \t")) < l
)
4118 opt
->params
[n
] = '|';
4124 /* This part associates a callback function to an option. */
4125 /* This function will be called when an instance of an option */
4127 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
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,
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
)
4154 opt
->data
= xrealloc(opt
->data
, nb_data
* sizeof(void *));
4155 opt
->data
[nb_data
- 1] = data
;
4157 opt
->nb_data
= nb_data
;
4160 fatal_internal("Unknown option %s.", ptr
);
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 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""" */
4172 constraint_t
* cstr
;
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
);
4203 fatal_internal("Unknown option %s.", ptr
);
4213 /* =============================================================== */
4214 /* This function provides a way to set the behaviour of a context. */
4215 /* =============================================================== */
4217 ctxopt_add_ctx_settings(settings s
, ...)
4226 /* Add a set of mutually incompatible options in a context. */
4227 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""" */
4228 case incompatibilities
:
4235 ptr
= va_arg(args
, char *);
4236 if ((ctx
= locate_ctx(ptr
)) != NULL
)
4238 ptr
= va_arg(args
, char *);
4239 list
= ctx
->incomp_list
;
4243 rtrim(str
, " \t", 0);
4245 n
= strcspn(str
, " \t");
4246 if (n
> 0 && n
< strlen(str
))
4247 ll_append(list
, str
);
4250 "Not enough incompatible options in the string: \"%s\".", str
);
4253 fatal_internal("Unknown context %s.", ptr
);
4257 /* Add functions which will be called when */
4258 /* entering and exiting a context. */
4259 /* """"""""""""""""""""""""""""""""""""""" */
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
)
4278 ctx
->data
= xrealloc(ctx
->data
, nb_data
* sizeof(void *));
4279 ctx
->data
[nb_data
- 1] = data
;
4281 ctx
->nb_data
= nb_data
;
4284 fatal_internal("Unknown context %s.", ptr
);