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",
361 if (cur_state
->cur_opt_par_name
!= NULL
)
363 "The parameter %s takes no arguments "
364 "or has too many arguments.\n",
365 cur_state
->cur_opt_par_name
);
369 if (cur_state
->pre_opt_par_name
!= NULL
)
370 fprintf(stderr
, "%s requires argument(s).\n",
371 cur_state
->pre_opt_par_name
);
373 fprintf(stderr
, "%s requires argument(s).\n",
374 cur_state
->cur_opt_par_name
);
378 if (cur_state
->pre_opt_par_name
!= NULL
)
380 "The parameter %s can only appear once in the context "
381 "introduced by %s.\n",
382 cur_state
->cur_opt_params
, cur_state
->ctx_par_name
);
385 "The parameter %s can only appear once "
386 "in the main context.\n",
387 cur_state
->cur_opt_params
);
391 fprintf(stderr
, "Unknown parameter %s.\n%s",
392 cur_state
->cur_opt_par_name
, errmsg
);
396 fprintf(stderr
, "The parameter %s is incompatible with %s.\n",
397 cur_state
->cur_opt_par_name
, errmsg
);
401 if (cur_state
->ctx_par_name
)
403 "The parameter %s must appear exactly %d times "
404 "in the context introduced by %s.\n",
405 cur_state
->cur_opt_params
, cur_state
->opts_count
,
406 cur_state
->ctx_par_name
);
409 "The parameter %s must appear exactly %d times "
410 "in the main context.\n",
411 cur_state
->cur_opt_params
, cur_state
->opts_count
);
415 if (cur_state
->ctx_par_name
)
417 "The parameter %s must appear less than %d times "
418 "in the context introduced by %s.\n",
419 cur_state
->cur_opt_params
, cur_state
->opts_count
,
420 cur_state
->ctx_par_name
);
423 "The parameter %s must appear less than %d times "
424 "in the main context.\n",
425 cur_state
->cur_opt_params
, cur_state
->opts_count
);
429 if (cur_state
->ctx_par_name
)
431 "The parameter %s must appear more than %d times "
432 "in the context introduced by %s.\n",
433 cur_state
->cur_opt_params
, cur_state
->opts_count
,
434 cur_state
->ctx_par_name
);
437 "The parameter %s must appear more than %d times "
438 "in the main context.\n",
439 cur_state
->cur_opt_params
, cur_state
->opts_count
);
443 fprintf(stderr
, "The parameter %s must have exactly %d arguments.\n",
444 cur_state
->cur_opt_par_name
, cur_state
->opt_args_count
);
448 fprintf(stderr
, "The parameter %s must have less than %d arguments.\n",
449 cur_state
->cur_opt_par_name
, cur_state
->opt_args_count
);
453 fprintf(stderr
, "The parameter %s must have more than %d arguments.\n",
454 cur_state
->cur_opt_par_name
, cur_state
->opt_args_count
);
462 /* CTXOPTUNKPAR should display the full usage to help the user follow */
463 /* the chaining of contexts when several possible contexts have been */
464 /* identified. Otherwise, errmsg is the empty string and the display of */
465 /* the current usage is enough. */
466 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
467 if (e
== CTXOPTUNKPAR
&& *errmsg
!= '\0')
468 ctxopt_disp_usage(continue_after
);
470 ctxopt_ctx_disp_usage(cur_state
->ctx_name
, continue_after
);
472 exit(e
); /* Exit with the error id e as return code. */
475 /* ********************************* */
476 /* Memory management implementation. */
477 /* ********************************* */
479 /* ================== */
480 /* Customized malloc. */
481 /* ================== */
488 real_size
= (size
> 0) ? size
: 1;
489 allocated
= malloc(real_size
);
490 if (allocated
== NULL
)
491 fatal_internal("Insufficient memory (attempt to malloc %lu bytes).\n",
492 (unsigned long int)size
);
497 /* ================== */
498 /* Customized calloc. */
499 /* ================== */
501 xcalloc(size_t n
, size_t size
)
506 size
= (size
> 0) ? size
: 1;
507 allocated
= calloc(n
, size
);
508 if (allocated
== NULL
)
509 fatal_internal("Insufficient memory (attempt to calloc %lu bytes).\n",
510 (unsigned long int)size
);
515 /* =================== */
516 /* Customized realloc. */
517 /* =================== */
519 xrealloc(void * p
, size_t size
)
523 allocated
= realloc(p
, size
);
524 if (allocated
== NULL
&& size
> 0)
525 fatal_internal("Insufficient memory (attempt to xrealloc %lu bytes).\n",
526 (unsigned long int)size
);
531 /* ==================================== */
532 /* strdup implementation using xmalloc. */
533 /* ==================================== */
535 xstrdup(const char * p
)
539 allocated
= xmalloc(strlen(p
) + 1);
540 strcpy(allocated
, p
);
545 /* =================================================== */
546 /* strndup implementation using xmalloc. */
547 /* This version guarantees that there is a final '\0'. */
548 /* =================================================== */
550 xstrndup(const char * str
, size_t len
)
554 p
= memchr(str
, '\0', len
);
559 p
= xmalloc(len
+ 1);
566 /* *************************** */
567 /* Linked list implementation. */
568 /* *************************** */
570 /* Linked list node structure. */
571 /* """"""""""""""""""""""""""" */
575 struct ll_node_s
* next
;
576 struct ll_node_s
* prev
;
579 /* Linked List structure. */
580 /* """""""""""""""""""""" */
588 /* ========================= */
589 /* Create a new linked list. */
590 /* ========================= */
594 ll_t
* ret
= xmalloc(sizeof(ll_t
));
600 /* =============================================== */
601 /* Free all the elements of a list (make it empty) */
602 /* NULL or a custom function may be used to free */
603 /* the sub components of the elements. */
604 /* =============================================== */
606 ll_free(ll_t
* const list
, void (*clean
)(void *))
611 /* Apply a custom cleaner if not NULL. */
612 /* """"""""""""""""""""""""""""""""""" */
614 clean(list
->head
->data
);
616 ll_delete(list
, list
->head
);
620 /* ==================================== */
621 /* Destroy a list and all its elements. */
622 /* ==================================== */
624 ll_destroy(ll_t
* list
, void (*clean
)(void *))
628 ll_free(list
, clean
);
633 /* ========================= */
634 /* Initialize a linked list. */
635 /* ========================= */
644 /* ===================================================== */
645 /* Allocate the space for a new node in the linked list. */
646 /* ===================================================== */
650 ll_node_t
* ret
= xmalloc(sizeof(ll_node_t
));
655 /* ==================================================================== */
656 /* Append a new node filled with its data at the end of the linked list */
657 /* The user is responsible for the memory management of the data. */
658 /* ==================================================================== */
660 ll_append(ll_t
* const list
, void * const data
)
664 node
= ll_new_node(); /* ll_new_node cannot return NULL because it *
665 | uses xmalloc which does not return if there *
666 | is an allocation error. */
671 node
->prev
= list
->tail
;
673 list
->tail
->next
= node
;
682 /* ================================================================== */
683 /* Put a new node filled with its data at the beginning of the linked */
685 /* The user is responsible for the memory management of the data. */
686 /* ================================================================== */
688 ll_prepend(ll_t
* const list
, void * const data
)
692 node
= ll_new_node(); /* ll_new_node cannot return NULL because it *
693 | uses xmalloc which does not return if there *
694 | is an allocation error. */
699 node
->next
= list
->head
;
701 list
->head
->prev
= node
;
710 /* ======================================================== */
711 /* Insert a new node before the specified node in the list. */
712 /* ======================================================== */
714 ll_insert_before(ll_t
* const list
, ll_node_t
* node
, void * const data
)
716 ll_node_t
* new_node
;
718 if (node
->prev
== NULL
)
719 ll_prepend(list
, data
);
722 new_node
= ll_new_node(); /* ll_new_node cannot return NULL because it *
723 | uses xmalloc which does not return if there *
724 | is an allocation error. */
726 new_node
->data
= data
;
727 new_node
->next
= node
;
728 new_node
->prev
= node
->prev
;
729 node
->prev
->next
= new_node
;
730 node
->prev
= new_node
;
736 /* ======================================================= */
737 /* Insert a new node after the specified node in the list. */
738 /* ======================================================= */
740 ll_insert_after(ll_t
* const list
, ll_node_t
* node
, void * const data
)
742 ll_node_t
* new_node
;
744 if (node
->next
== NULL
)
745 ll_append(list
, data
);
748 new_node
= ll_new_node(); /* ll_new_node cannot return NULL because it *
749 | uses xmalloc which does not return if there *
750 | is an allocation error. */
752 new_node
->data
= data
;
753 new_node
->prev
= node
;
754 new_node
->next
= node
->next
;
755 node
->next
->prev
= new_node
;
756 node
->next
= new_node
;
762 /* ================================================================= */
763 /* Remove a node from a linked list */
764 /* The memory taken by the deleted node must be freed by the caller. */
765 /* ================================================================= */
767 ll_delete(ll_t
* const list
, ll_node_t
* node
)
769 if (list
->head
== list
->tail
)
771 if (list
->head
!= NULL
)
772 list
->head
= list
->tail
= NULL
;
776 else if (node
->prev
== NULL
)
778 list
->head
= node
->next
;
779 list
->head
->prev
= NULL
;
781 else if (node
->next
== NULL
)
783 list
->tail
= node
->prev
;
784 list
->tail
->next
= NULL
;
788 node
->next
->prev
= node
->prev
;
789 node
->prev
->next
= node
->next
;
799 #if 0 /* Unused yet */
800 /* ======================================================================== */
801 /* Find a node in the list containing data. Return the node pointer or NULL */
803 /* A comparison function must be provided to compare a and b (strcmp like). */
804 /* ======================================================================== */
806 ll_find(ll_t
* const list
, void * const data
,
807 int (*cmpfunc
)(const void * a
, const void * b
))
811 if (NULL
== (node
= list
->head
))
816 if (0 == cmpfunc(node
->data
, data
))
818 } while (NULL
!= (node
= node
->next
));
824 /* ==================================================================== */
825 /* Allocate and fill an array of strings from a list. */
827 /* 1) The list node must contain strings (char *) */
828 /* 2) The strings in the resulting array MUST NOT be freed as the are */
829 /* NOT copied from the strings of the list. */
831 /* IN list : The list from which the array is generated */
832 /* IN start_node : The node of the list which will be the first node to */
833 /* consider to create the array */
834 /* OUT: count : The number of elements of the resulting array. */
835 /* OUT: array : The resulting array or NULL if the list is empty. */
836 /* RC : : The number of elements of the resulting array. */
837 /* ==================================================================== */
839 ll_strarray(ll_t
* list
, ll_node_t
* start_node
, int * count
, char *** array
)
848 if (list
== NULL
|| node
== NULL
)
855 *array
= xmalloc((list
->len
+ 1) * sizeof(char *));
858 (*array
)[n
++] = (char *)(node
->data
);
864 (*array
)[*count
] = NULL
;
869 /* ******************************************************************* */
870 /* BST (search.h compatible) implementation. */
872 /* Tree search generalized from Knuth (6.2.2) Algorithm T just like */
873 /* the AT&T man page says. */
875 /* Written by reading the System V Interface Definition, not the code. */
877 /* Totally public domain. */
878 /* ******************************************************************* */
883 struct bst_s
* llink
;
884 struct bst_s
* rlink
;
887 #if 0 /* Unused yet */
888 /* =========================== */
889 /* Delete node with given key. */
890 /* =========================== */
892 bst_delete(const void * vkey
, void ** vrootp
,
893 int (*compar
)(const void *, const void *))
895 bst_t
** rootp
= (bst_t
**)vrootp
;
899 if (rootp
== NULL
|| (p
= *rootp
) == NULL
)
902 while ((cmp
= (*compar
)(vkey
, (*rootp
)->key
)) != 0)
905 rootp
= (cmp
< 0) ? &(*rootp
)->llink
/* follow llink branch */
906 : &(*rootp
)->rlink
; /* follow rlink branch */
908 return NULL
; /* key not found */
910 r
= (*rootp
)->rlink
; /* D1: */
911 if ((q
= (*rootp
)->llink
) == NULL
) /* Left NULL? */
914 { /* Right link is NULL? */
915 if (r
->llink
== NULL
)
916 { /* D2: Find successor */
921 { /* D3: Find NULL link */
922 for (q
= r
->llink
; q
->llink
!= NULL
; q
= r
->llink
)
925 q
->llink
= (*rootp
)->llink
;
926 q
->rlink
= (*rootp
)->rlink
;
930 free(*rootp
); /* D4: Free node */
931 *rootp
= q
; /* link parent to new node */
936 /* ===================================================================== */
937 /* Destroy a tree. */
938 /* The clean function pointer can be NULL, in this case the node content */
940 /* ===================================================================== */
942 bst_destroy(void * vrootp
, void (*clean
)(void *))
944 bst_t
* root
= (bst_t
*)vrootp
;
949 bst_destroy(root
->llink
, clean
);
950 bst_destroy(root
->rlink
, clean
);
953 clean((void *)root
->key
);
958 /* ========================= */
959 /* Find a node, or return 0. */
960 /* ========================= */
962 bst_find(const void * vkey
, void * const * vrootp
,
963 int (*compar
)(const void *, const void *))
965 bst_t
* const * rootp
= (bst_t
* const *)vrootp
;
970 while (*rootp
!= NULL
)
974 if ((r
= (*compar
)(vkey
, (*rootp
)->key
)) == 0) /* T2: */
975 return *rootp
; /* key found */
976 rootp
= (r
< 0) ? &(*rootp
)->llink
/* T3: follow left branch */
977 : &(*rootp
)->rlink
; /* T4: follow right branch */
982 /* ======================================= */
983 /* Find or inserts datum into search tree. */
984 /* ======================================= */
986 bst_search(void * vkey
, void ** vrootp
,
987 int (*compar
)(const void *, const void *))
990 bst_t
** rootp
= (bst_t
**)vrootp
;
995 while (*rootp
!= NULL
)
999 if ((r
= (*compar
)(vkey
, (*rootp
)->key
)) == 0) /* T2: */
1000 return *rootp
; /* we found it! */
1002 rootp
= (r
< 0) ? &(*rootp
)->llink
/* T3: follow left branch */
1003 : &(*rootp
)->rlink
; /* T4: follow right branch */
1006 q
= xmalloc(sizeof(bst_t
)); /* T5: key not found */
1008 { /* make new node */
1009 *rootp
= q
; /* link new node to old */
1010 q
->key
= vkey
; /* initialize new node */
1011 q
->llink
= q
->rlink
= NULL
;
1016 /* ========================= */
1017 /* Walk the nodes of a tree. */
1018 /* ========================= */
1020 bst_walk_recurse(const bst_t
* root
,
1021 void (*action
)(const void *, walk_order_e
, int), int level
)
1023 if (root
->llink
== NULL
&& root
->rlink
== NULL
)
1024 (*action
)(root
, leaf
, level
);
1027 (*action
)(root
, preorder
, level
);
1028 if (root
->llink
!= NULL
)
1029 bst_walk_recurse(root
->llink
, action
, level
+ 1);
1030 (*action
)(root
, postorder
, level
);
1031 if (root
->rlink
!= NULL
)
1032 bst_walk_recurse(root
->rlink
, action
, level
+ 1);
1033 (*action
)(root
, endorder
, level
);
1038 bst_walk(const void * vroot
, void (*action
)(const void *, walk_order_e
, int))
1040 if (vroot
!= NULL
&& action
!= NULL
)
1041 bst_walk_recurse(vroot
, action
, 0);
1044 /* ************************ */
1045 /* Various implementations. */
1046 /* ************************ */
1048 /* ======================== */
1049 /* Trim leading characters. */
1050 /* ======================== */
1052 ltrim(char * str
, const char * trim_str
)
1054 size_t len
= strlen(str
);
1055 size_t begin
= strspn(str
, trim_str
);
1059 for (i
= begin
; i
<= len
; ++i
)
1060 str
[i
- begin
] = str
[i
];
1063 /* ================================================= */
1064 /* Trim trailing characters. */
1065 /* The resulting string will have at least min bytes */
1066 /* even if trailing spaces remain. */
1067 /* ================================================= */
1069 rtrim(char * str
, const char * trim_str
, size_t min
)
1071 size_t len
= strlen(str
);
1072 while (len
> min
&& strchr(trim_str
, str
[len
- 1]))
1076 /* ================================================== */
1077 /* Count the number of occurrences of the character c */
1078 /* in the string str. */
1079 /* The str pointer is assumed to be not NULL. */
1080 /* ================================================== */
1082 strchrcount(char * str
, char c
)
1093 /* =============================================== */
1094 /* Is the string str2 a prefix of the string str1? */
1095 /* =============================================== */
1097 strpref(char * str1
, char * str2
)
1099 while (*str1
!= '\0' && *str1
== *str2
)
1105 return *str2
== '\0';
1108 /* ========================== */
1109 /* Like strcmp ignoring case. */
1110 /* ========================== */
1112 stricmp(const char * s1
, const char * s2
)
1114 while (tolower((unsigned char)*s1
) == tolower((unsigned char)*s2
))
1123 return (int)tolower((unsigned char)*s1
) - (int)tolower((unsigned char)*s2
);
1126 /* ======================================================================== */
1127 /* Strings concatenation with dynamic memory allocation. */
1128 /* IN : a variable number of char * arguments with NULL terminating */
1130 /* The first one must have been dynamically allocated and is mandatory */
1132 /* Returns a new allocated string containing the concatenation of all */
1133 /* the arguments. It is the caller's responsibility to free the resulting */
1135 /* ======================================================================== */
1137 strappend(char * str
, ...)
1143 l
= 1 + strlen(str
);
1144 va_start(args
, str
);
1146 s
= va_arg(args
, char *);
1151 s
= va_arg(args
, char *);
1156 str
= xrealloc(str
, l
);
1158 va_start(args
, str
);
1159 s
= va_arg(args
, char *);
1164 s
= va_arg(args
, char *);
1171 /* ====================================================================== */
1172 /* Public domain strtok_r() by Charlie Gordon. */
1173 /* from comp.lang.c 9/14/2007 */
1174 /* http://groups.google.com/group/comp.lang.c/msg/2ab1ecbb86646684 */
1176 /* (Declaration that it's public domain): */
1177 /* http://groups.google.com/group/comp.lang.c/msg/7c7b39328fefab9c */
1179 /* Also, fixed by Fletcher T. Penney --- added the "return NULL" when */
1181 /* ====================================================================== */
1183 xstrtok_r(char * str
, const char * delim
, char ** end
)
1193 str
+= strspn(str
, delim
);
1200 str
+= strcspn(str
, delim
);
1210 /* ===================================================================== */
1211 /* Put the first word of str, truncated to len characters, in buf. */
1212 /* Return a pointer in str pointing just after the word. */
1213 /* buf must have been pre-allocated to accept at least len+1 characters. */
1214 /* Note that buf can contains a sting full of spaces is str was not */
1215 /* trimmed before the call. */
1216 /* ===================================================================== */
1218 get_word(char * str
, char * buf
, size_t len
)
1224 while (*s
&& isspace(*s
))
1227 /* Set the new string start. */
1228 /* """"""""""""""""""""""""" */
1233 while (*s
&& !isspace(*s
) && s
- str
< len
)
1236 strncpy(buf
, str
, s
- str
);
1242 /* ==================================================================== */
1243 /* Return 1 is value is "1" or "yes" (ignoring case). */
1244 /* Return 0 is value is "0" or "no" (ignoring case). */
1245 /* If value has another value, then set invalid to 1 and also return 0 */
1246 /* invalid is set to 0i in all the other cases. */
1247 /* ==================================================================== */
1249 eval_yes(char * value
, int * invalid
)
1253 if (strcmp(value
, "1") == 0 || stricmp(value
, "yes") == 0)
1255 else if (strcmp(value
, "0") != 0 && stricmp(value
, "no") != 0)
1261 /* =========================================================== */
1262 /* Fill an array of strings from the words composing a string. */
1264 /* str: initial string which will be altered. */
1265 /* args: array of pointers to the start of the words in str. */
1266 /* max: maximum number of words used before giving up. */
1267 /* return: the number of words (<=max). */
1268 /* =========================================================== */
1270 str2argv(char * str
, char ** args
, int max
)
1279 while (*str
== ' ' || *str
== '\t')
1285 args
[nb_args
] = str
;
1288 while (*str
&& (*str
!= ' ') && (*str
!= '\t'))
1295 /* ********************** */
1296 /* ctxopt implementation. */
1297 /* ********************** */
1299 static int ctxopt_initialized
= 0; /* cap_init has not yet been called */
1301 /* Flags structure initialized by ctxopt_init. */
1302 /* """"""""""""""""""""""""""""""""""""""""""" */
1305 int stop_if_non_option
;
1306 int allow_abbreviations
;
1309 /* Context structure. */
1310 /* """""""""""""""""" */
1314 ll_t
* opt_list
; /* list of options allowed in this context. */
1315 ll_t
* incomp_list
; /* list of strings containing incompatible names *
1316 | of options separated by spaces or tabs. */
1317 int (*action
)(char * name
, int type
, char * new_ctx
, int ctx_nb_data
,
1324 /* https://textik.com/#488ce3649b6c60f5 */
1326 /* +--------------+ */
1327 /* |first_ctx_inst| */
1328 /* +---+----------+ */
1330 /* +--v-----+ +--------+ +--------+ +-----+ */
1331 /* +---+-->ctx_inst+------>opt_inst+----->opt_inst+------> ... | */
1332 /* | | +-+------+ +----+---+ +----+---+ +-----+ */
1334 /* | | +-v------+ | | */
1335 /* | +--+ctx_inst<-----------+ | */
1336 /* | +-+------+ | */
1338 /* | +-v------+ | */
1339 /* +------+ctx_inst<--------------------------+ */
1346 /* Option structure. */
1347 /* """"""""""""""""" */
1350 char * name
; /* option name. */
1351 char * next_ctx
; /* new context this option may lead to */
1352 ll_t
* ctx_list
; /* list of contexts allowing this option. */
1353 char * params
; /* string containing all the parameters of *
1356 void (*action
)( /* The option associated action. */
1357 char * ctx_name
, /* context name. */
1358 char * opt_name
, /* option name. */
1359 char * par
, /* option parameter. */
1360 int nb_args
, /* number of arguments. */
1361 char ** args
, /* option arguments. */
1362 int nb_opt_data
, /* number of option data pointers. */
1363 void ** opt_data
, /* option data pointers. */
1364 int nb_ctx_data
, /* nb of current context data ptrs. */
1365 void ** ctx_data
/* current context data pointers. */
1368 int nb_data
; /* number of the data pointers passed as argument to action. */
1369 void ** data
; /* array of data pointers passed as argument to action. */
1371 int args
; /* 1 if this option takes arguments else 0. */
1372 int optional
; /* 1 if the option is optional, else 0. */
1373 int multiple
; /* 1 if the option can appear more than one time in a *
1374 | context, else 0. */
1376 int opt_count_matter
; /* 1 if we must restrict the count, else 0. */
1377 int occurrences
; /* Number of option occurrences in a context. */
1378 char opt_count_oper
; /* <, = or > */
1379 unsigned opt_count_mark
; /* Value to be compared to with opt_count_oper. */
1381 char * arg
; /* symbolic text after # describing the option argument. */
1383 int optional_args
; /* 1 of option is optional else 0. */
1384 int multiple_args
; /* 1 is option can appear more than once in a context *
1387 int opt_args_count_matter
; /* 1 if count is rescticted, else 0. */
1388 char opt_args_count_oper
; /* <, = or > */
1389 unsigned opt_args_count_mark
; /* Value to be compared to with *
1390 | opt_count_oper. */
1392 int eval_first
; /* 1 if this option must be evaluated before the options *
1393 | without this mark. */
1395 ll_t
* eval_before_list
; /* List of pointers on options which must be *
1396 | evaluated before this option. */
1398 ll_t
* constraints_list
; /* List of constraint check functions pointers. */
1401 /* Context instance structure. */
1402 /* """"""""""""""""""""""""""" */
1405 ctx_t
* ctx
; /* the context whose this is an instance of */
1406 ctx_inst_t
* prev_ctx_inst
; /* ctx_inst of the opt_inst which led to the *
1407 | creation of this ctx_inst structure. */
1408 opt_inst_t
* gen_opt_inst
; /* opt_inst which led to the creation of a *
1409 | instance of this structure. */
1410 ll_t
* incomp_bst_list
; /* list of seen_opt_t BST. */
1411 void * seen_opt_bst
; /* tree of seen_opt_t. */
1412 ll_t
* opt_inst_list
; /* The list of option instances in this *
1413 | context instance. */
1414 char * par_name
; /* parameter which created this instance. */
1417 /* Option instance structure. */
1418 /* """""""""""""""""""""""""" */
1421 opt_t
* opt
; /* The option this is an instance of. */
1422 char * opt_name
; /* The option which led to this creation. */
1423 char * par
; /* The parameter which led to this creation. */
1424 ll_t
* values_list
; /* The list of arguments of this option. */
1425 ctx_inst_t
* next_ctx_inst
; /* The new context instance this option. *
1426 | instance may create. */
1429 /* Structure used to check if an option has bee seen or not */
1430 /* in a context instance. */
1431 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""" */
1434 opt_t
* opt
; /* The concerned option. */
1435 char * par
; /* Parameter which led to the making of this structure. */
1436 int seen
; /* 1 if seen in the context instances, else 0. */
1439 /* Parameter structure which links a parameter to the option it belongs to. */
1440 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
1443 char * name
; /* Parameter name (with the leading -). */
1444 opt_t
* opt
; /* Attached option. */
1447 /* Constraint structure. */
1448 /* """"""""""""""""""""" */
1451 int (*constraint
)(int nb_args
, char ** args
, char * value
, char * parameter
);
1454 char * to_free
; /* pointer to the original string in which the array in *
1455 | args points to. This poinnter is kept there to allow *
1456 | it to be freed. */
1459 state_t
* cur_state
= NULL
; /* Current analysis state. */
1460 static ll_t
* cmdline_list
; /* List of interpreted CLI words *
1461 | serves as the basis for the *
1462 | analysis of the parameters. */
1463 static ctx_t
* main_ctx
= NULL
; /* initial context. */
1464 static ctx_inst_t
* first_ctx_inst
= NULL
; /* Pointer to the fist context *
1465 | instance which holds the *
1466 | options instances. */
1467 static ll_t
* ctx_inst_list
= NULL
; /* List of the context instances. */
1469 static flags_t flags
= { 0, 1 };
1471 /* ======================================================= */
1472 /* Parse a string for the next matching token. */
1474 /* s: string to parse. */
1475 /* token: pre_allocated array of max tok_len characters. */
1476 /* pattern: scanf type pattern token must match. */
1477 /* pos: number of characters successfully parsed in s. */
1479 /* Returns: a pointer to the first unread character or */
1480 /* to he terminating \0. */
1481 /* ======================================================= */
1483 strtoken(char * s
, char * token
, size_t tok_len
, char * pattern
, int * pos
)
1485 char * full_pattern
;
1491 n
= snprintf(len
, 3, "%zu", tok_len
);
1495 full_pattern
= xmalloc(strlen(pattern
) + n
+ 4);
1497 strcpy(full_pattern
, "%");
1498 strcat(full_pattern
, len
);
1499 strcat(full_pattern
, pattern
);
1500 strcat(full_pattern
, "%n");
1502 n
= sscanf(s
, full_pattern
, token
, pos
);
1512 /* ****************************************** */
1513 /* Various comparison and deletion functions. */
1514 /* ****************************************** */
1517 ctx_compare(const void * c1
, const void * c2
)
1519 return strcmp(((ctx_t
*)c1
)->name
, ((ctx_t
*)c2
)->name
);
1522 /* =========================== */
1523 /* Free a context_bst element. */
1524 /* =========================== */
1533 ll_destroy(ctx
->opt_list
, NULL
);
1534 ll_destroy(ctx
->incomp_list
, free
);
1535 bst_destroy(ctx
->par_bst
, par_free
);
1540 /* ============================= */
1541 /* Free a ctx_inst_list element. */
1542 /* ============================= */
1544 ctx_inst_free(void * ci
)
1546 ctx_inst_t
* ctx_inst
= ci
;
1548 free(ctx_inst
->par_name
);
1549 ll_destroy(ctx_inst
->incomp_bst_list
, incomp_bst_free
);
1550 bst_destroy(ctx_inst
->seen_opt_bst
, seen_opt_free
);
1551 ll_destroy(ctx_inst
->opt_inst_list
, opt_inst_free
);
1556 /* ============================= */
1557 /* Free a opt_inst_list element. */
1558 /* ============================= */
1560 opt_inst_free(void * oi
)
1562 opt_inst_t
* opt_inst
= oi
;
1564 ll_destroy(opt_inst
->values_list
, NULL
);
1569 /* ================================== */
1570 /* Compare two seen_opt_bst elements. */
1571 /* ================================== */
1573 seen_opt_compare(const void * so1
, const void * so2
)
1577 o1
= ((seen_opt_t
*)so1
)->opt
;
1578 o2
= ((seen_opt_t
*)so2
)->opt
;
1580 return strcmp(o1
->name
, o2
->name
);
1583 /* ============================ */
1584 /* Free a seen_opt_bst element. */
1585 /* ============================ */
1587 seen_opt_free(void * so
)
1589 seen_opt_t
* seen_opt
= so
;
1591 free(seen_opt
->par
);
1596 /* =========================== */
1597 /* Free an incomp_bst element. */
1598 /* =========================== */
1600 incomp_bst_free(void * b
)
1604 bst_destroy(bst
, NULL
);
1607 /* ================================= */
1608 /* Compare two options_bst elements. */
1609 /* ================================= */
1611 opt_compare(const void * o1
, const void * o2
)
1613 return strcmp(((opt_t
*)o1
)->name
, ((opt_t
*)o2
)->name
);
1616 /* ============================= */
1617 /* Free an options_bst elements. */
1618 /* ============================= */
1625 free(opt
->next_ctx
);
1630 ll_destroy(opt
->ctx_list
, NULL
);
1631 ll_destroy(opt
->constraints_list
, constraint_free
);
1636 /* ============================= */
1637 /* Compare two par_bst elements. */
1638 /* ============================= */
1640 par_compare(const void * a1
, const void * a2
)
1642 return strcmp(((par_t
*)a1
)->name
, ((par_t
*)a2
)->name
);
1645 /* ======================= */
1646 /* Free a par_bst element. */
1647 /* ======================= */
1658 /* ================================ */
1659 /* Free a constraints_list element. */
1660 /* ================================ */
1662 constraint_free(void * c
)
1664 constraint_t
* cstr
= c
;
1667 free(cstr
->to_free
);
1672 /* ******************************************************************** */
1673 /* Helper functions to locate contexts, options and parameters in a BST */
1674 /* by their names. */
1675 /* ******************************************************************** */
1678 locate_ctx(char * name
)
1685 if ((node
= bst_find(&ctx
, &contexts_bst
, ctx_compare
)) == NULL
)
1692 locate_opt(char * name
)
1699 if ((node
= bst_find(&opt
, &options_bst
, opt_compare
)) == NULL
)
1706 locate_par(char * name
, ctx_t
* ctx
)
1710 void * bst
= ctx
->par_bst
;
1714 if ((node
= bst_find(&par
, &bst
, par_compare
)) == NULL
)
1720 /* =================================================================== */
1721 /* Utility function to format and print the options present in a list. */
1723 /* IN list : a list of options. */
1724 /* OUT has_* : a set of flags which will determine the content of the */
1725 /* explanation given after the formatted printing of the */
1727 /* =================================================================== */
1729 print_options(ll_t
* list
, int * has_optional
, int * has_ellipsis
,
1730 int * has_rule
, int * has_generic_arg
, int * has_ctx_change
,
1731 int * has_early_eval
)
1733 ll_node_t
* node
= list
->head
;
1738 line
= xstrdup(" ");
1740 while (node
!= NULL
)
1742 option
= xstrdup("");
1747 option
= strappend(option
, "[", (char *)0);
1751 if (opt
->eval_first
)
1753 option
= strappend(option
, "*", (char *)0);
1754 *has_early_eval
= 1;
1757 option
= strappend(option
, opt
->params
, (char *)0);
1759 if (opt
->next_ctx
!= NULL
)
1761 option
= strappend(option
, ">", opt
->next_ctx
, (char *)0);
1762 *has_ctx_change
= 1;
1767 if (opt
->opt_count_oper
!= '\0')
1771 o
[0] = opt
->opt_count_oper
;
1773 snprintf(m
, 3, "%u", opt
->opt_count_mark
);
1774 option
= strappend(option
, "...", o
, m
, (char *)0);
1778 option
= strappend(option
, "...", (char *)0);
1785 if (*(opt
->arg
) == '#')
1786 *has_generic_arg
= 1;
1788 option
= strappend(option
, " ", (char *)0);
1790 if (opt
->optional_args
)
1792 option
= strappend(option
, "[", opt
->arg
, (char *)0);
1796 option
= strappend(option
, opt
->arg
, (char *)0);
1798 if (opt
->multiple_args
)
1800 if (opt
->opt_args_count_oper
!= '\0')
1804 o
[0] = opt
->opt_args_count_oper
;
1806 snprintf(m
, 3, "%u", opt
->opt_args_count_mark
);
1807 option
= strappend(option
, "...", o
, m
, (char *)0);
1811 option
= strappend(option
, "...", (char *)0);
1815 if (opt
->optional_args
)
1816 option
= strappend(option
, "]", (char *)0);
1819 option
= strappend(option
, "]", (char *)0);
1821 if (strlen(line
) + 1 + strlen(option
) < 80)
1822 line
= strappend(line
, option
, " ", (char *)0);
1825 printf("%s\n", line
);
1827 line
= strappend(line
, option
, " ", (char *)0);
1835 printf("%s\n", line
);
1840 /* ==================================================== */
1841 /* Explain the special syntactic symbols present in the */
1842 /* generated usage messages. */
1843 /* ==================================================== */
1845 print_explanations(int has_early_eval
, int has_ctx_change
, int has_generic_arg
,
1846 int has_optional
, int has_ellipsis
, int has_rule
)
1848 if (has_early_eval
|| has_ctx_change
|| has_generic_arg
|| has_optional
1849 || has_ellipsis
|| has_rule
)
1851 printf("\nExplanation of the syntax used above:\n");
1852 printf("Only the parameters (prefixed by -) and the arguments, if any, "
1853 "must be entered.\n");
1854 printf("The following is just there to explain the other symbols "
1858 printf("* : the parameters for this option will be "
1859 "evaluated first.\n");
1862 "> : The context after this symbol will become the next "
1864 if (has_generic_arg
)
1865 printf("#tag : argument tag giving a clue to its meaning.\n");
1868 "[...] : the object between square brackets is optional.\n");
1870 printf("... : several occurrences of the previous object "
1873 printf("[<|=|>]number: rules constraining the number of "
1874 "parameters/arguments.\n");
1878 /* ************************************************************ */
1879 /* Various utilities and callback functions called when walking */
1880 /* through a BST. */
1881 /* ************************************************************ */
1884 bst_seen_opt_cb(const void * node
, walk_order_e kind
, int level
)
1886 seen_opt_t
* seen_opt
= ((bst_t
*)node
)->key
;
1888 if (kind
== postorder
|| kind
== leaf
)
1890 if ((!seen_opt
->opt
->optional
) && seen_opt
->seen
== 0)
1893 user_string
= strappend(user_string
, seen_opt
->opt
->params
, " ",
1900 bst_seen_opt_seen_cb(const void * node
, walk_order_e kind
, int level
)
1902 seen_opt_t
* seen_opt
= ((bst_t
*)node
)->key
;
1904 if (kind
== postorder
|| kind
== leaf
)
1905 if (seen_opt
->seen
== 1)
1908 user_object
= seen_opt
->par
;
1913 bst_print_ctx_cb(const void * node
, walk_order_e kind
, int level
)
1915 ctx_t
* ctx
= main_ctx
;
1916 ctx_t
* cur_ctx
= ((bst_t
*)node
)->key
;
1920 int has_optional
= 0;
1921 int has_ellipsis
= 0;
1923 int has_generic_arg
= 0;
1924 int has_ctx_change
= 0;
1925 int has_early_eval
= 0;
1927 if (kind
== postorder
|| kind
== leaf
)
1928 if (strcmp(ctx
->name
, cur_ctx
->name
) != 0)
1930 list
= cur_ctx
->opt_list
;
1932 printf("\nAllowed options in the context %s:\n", cur_ctx
->name
);
1933 print_options(list
, &has_optional
, &has_ellipsis
, &has_rule
,
1934 &has_generic_arg
, &has_ctx_change
, &has_early_eval
);
1939 bst_check_opt_cb(const void * node
, walk_order_e kind
, int level
)
1941 opt_t
* opt
= ((bst_t
*)node
)->key
;
1943 if (kind
== postorder
|| kind
== leaf
)
1945 if (opt
->params
== NULL
) /* opt must have associated parameters. */
1946 fatal_internal("Option %s has no registered parameter.\n", opt
->name
);
1948 if (opt
->action
== NULL
) /* opt must have an action. */
1949 fatal_internal("Option %s has no registered action.\n", opt
->name
);
1954 bst_match_par_cb(const void * node
, walk_order_e kind
, int level
)
1956 ctx_t
* ctx
= ((bst_t
*)node
)->key
;
1958 if (kind
== postorder
|| kind
== leaf
)
1960 char * str
= xstrdup(user_string
);
1962 while (*str
!= '\0')
1964 if (locate_par(str
, ctx
) != NULL
)
1966 if (*user_string2
== '\0')
1967 user_string2
= strappend(user_string2
, "- ", ctx
->name
, (char *)0);
1969 user_string2
= strappend(user_string2
, "\n- ", ctx
->name
, (char *)0);
1972 str
[strlen(str
) - 1] = '\0';
1979 match_prefix_cb(const void * node
, walk_order_e kind
, int level
)
1981 par_t
* par
= ((bst_t
*)node
)->key
;
1983 if (kind
== postorder
|| kind
== leaf
)
1984 if (strpref(par
->name
, (char *)user_object
))
1987 user_string
= strappend(user_string
, par
->name
, " ", (char *)0);
1991 /* ====================================================================== */
1992 /* A parameter may not be separated from its first option by spaces, in */
1993 /* this case this function looks for a valid flag as a prefix and splits */
1994 /* the command line queue (eg: "-pa1" -> "-pa" "1" if "-pa" is a valid */
1997 /* IN word : the word to be checked. */
1998 /* IN ctx : the context in which the flag indexed by the word is to be */
2000 /* OUT pos : the offset in word pointing just after the matching prefix. */
2001 /* OUT opt : a pointer to the option associated with the new parameter */
2002 /* or NULL if none is found. */
2004 /* The returned pointer must be freed by the caller. */
2005 /* ====================================================================== */
2007 look_for_valid_prefix_in_word(char * word
, ctx_t
* ctx
, int * pos
, opt_t
** opt
)
2012 par_t tmp_par
= { 0 };
2018 new = xstrdup(word
);
2024 } while ((par
= locate_par(tmp_par
.name
, ctx
)) == NULL
&& len
> 2);
2043 /* ============================================================= */
2044 /* If par_name is an unique abbreviation of an exiting parameter */
2045 /* in the context ctx, then return this parameter. */
2046 /* ============================================================= */
2048 abbrev_expand(char * par_name
, ctx_t
* ctx
)
2050 user_object
= par_name
;
2053 *user_string
= '\0';
2054 bst_walk(ctx
->par_bst
, match_prefix_cb
);
2055 rtrim(user_string
, " ", 0);
2057 /* The previous bst_walk has built a string of blank separated parameters */
2058 /* all having par_name as prefix. This string is put in the user_string */
2059 /* exchange zone. The number of these words in put in user_rc. */
2060 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2061 if (user_rc
== 1) /* The number of matching abbreviations. */
2062 return xstrdup(user_string
);
2063 else /* There is at least tho defined parameters starting with par_name. */
2069 void * tmp_opt_bst
= NULL
;
2071 /* Find all the options corresponding to these words and store them */
2072 /* without duplication in a temporary BST. Only their resulting count */
2074 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2075 s
= first_s
= strtok(user_string
, " "); /* first_s holds a copy of *
2076 | the first word. */
2079 par
= locate_par(s
, ctx
);
2082 if (bst_find(opt
, &tmp_opt_bst
, opt_compare
) == NULL
)
2084 /* This option as not already been seen */
2085 /* store it and increase the seen counter. */
2086 /* """"""""""""""""""""""""""""""""""""""" */
2087 bst_search(opt
, &tmp_opt_bst
, opt_compare
);
2090 s
= strtok(NULL
, " ");
2093 /* Clean the temporary BST without removing the pointer */
2094 /* to the real options. */
2095 /* """""""""""""""""""""""""""""""""""""""""""""""""""" */
2096 if (tmp_opt_bst
!= NULL
)
2097 bst_destroy(tmp_opt_bst
, NULL
);
2100 /* All the abbreviation are leading to only one option */
2101 /* We can just continue as in the previous case. */
2102 /* """"""""""""""""""""""""""""""""""""""""""""""""""" */
2103 return xstrdup(first_s
);
2109 /* ================================================================ */
2110 /* Terminate the program if mandatory options required by a context */
2111 /* are not present. */
2112 /* ================================================================ */
2114 check_for_missing_mandatory_opt(ctx_inst_t
* ctx_inst
, char * opt_par
)
2118 if (has_unseen_mandatory_opt(ctx_inst
, &missing
))
2119 fatal(CTXOPTMISPAR
, missing
);
2122 /* ====================================================== */
2123 /* Return 1 if at least one mandatory option was not seen */
2124 /* when quitting a context, else 0. */
2125 /* ====================================================== */
2127 has_unseen_mandatory_opt(ctx_inst_t
* ctx_inst
, char ** missing
)
2130 *user_string
= '\0';
2132 bst_walk(ctx_inst
->seen_opt_bst
, bst_seen_opt_cb
);
2133 rtrim(user_string
, " ", 0);
2135 *missing
= user_string
;
2137 return user_rc
? 1 : 0;
2140 /* ========================================================================= */
2141 /* This function terminates the program if an option or its arguments do not */
2142 /* conform to its occurrences constraint. */
2143 /* There constraints can appear by trailing >, < or = in their definition */
2144 /* given in ctxopt_new_ctx. */
2145 /* ========================================================================= */
2147 check_for_occurrences_issues(ctx_inst_t
* ctx_inst
)
2149 ctx_t
* ctx
= ctx_inst
->ctx
;
2152 opt_inst_t
* opt_inst
;
2153 char * cur_opt_params
= cur_state
->cur_opt_params
;
2154 char * cur_opt_par_name
= cur_state
->cur_opt_par_name
;
2156 /* Checks options. */
2157 /* """"""""""""""" */
2158 node
= ctx
->opt_list
->head
;
2160 while (node
!= NULL
)
2164 /* Update current_state. */
2165 /* """"""""""""""""""""" */
2166 cur_state
->cur_opt_params
= opt
->params
;
2167 cur_state
->opts_count
= opt
->opt_count_mark
;
2168 cur_state
->opt_args_count
= opt
->opt_args_count_mark
;
2170 if (opt
->opt_count_matter
)
2171 switch (opt
->opt_count_oper
)
2174 if (opt
->occurrences
> 0 && opt
->opt_count_mark
!= opt
->occurrences
)
2175 fatal(CTXOPTCTEOPT
, NULL
);
2179 if (opt
->occurrences
> 0 && opt
->opt_count_mark
<= opt
->occurrences
)
2180 fatal(CTXOPTCTLOPT
, NULL
);
2184 if (opt
->occurrences
> 0 && opt
->opt_count_mark
>= opt
->occurrences
)
2185 fatal(CTXOPTCTGOPT
, NULL
);
2192 /* Checks arguments. */
2193 /* """"""""""""""""" */
2194 node
= ctx_inst
->opt_inst_list
->head
;
2195 while (node
!= NULL
)
2197 opt_inst
= node
->data
;
2198 opt
= opt_inst
->opt
;
2200 /* Update current_state. */
2201 /* """"""""""""""""""""" */
2202 cur_state
->cur_opt_par_name
= opt_inst
->par
;
2203 cur_state
->opts_count
= opt
->opt_count_mark
;
2204 cur_state
->opt_args_count
= opt
->opt_args_count_mark
;
2206 int nb_values
= opt_inst
->values_list
->len
; /* Number of arguments of opt */
2208 if (opt
->opt_args_count_matter
)
2209 switch (opt
->opt_args_count_oper
)
2212 if (nb_values
> 0 && opt
->opt_args_count_mark
!= nb_values
)
2213 fatal(CTXOPTCTEARG
, NULL
);
2217 if (nb_values
> 0 && opt
->opt_args_count_mark
<= nb_values
)
2218 fatal(CTXOPTCTLARG
, NULL
);
2222 if (nb_values
> 0 && opt
->opt_args_count_mark
>= nb_values
)
2223 fatal(CTXOPTCTGARG
, NULL
);
2229 cur_state
->cur_opt_params
= cur_opt_params
;
2230 cur_state
->cur_opt_par_name
= cur_opt_par_name
;
2233 /* ======================================================================== */
2234 /* Parse a strings describing options and some of their characteristics */
2235 /* The input string must have follow some rules like in the examples below: */
2237 /* "opt_name1 opt_name2" */
2238 /* "[opt_name1] opt_name2" */
2239 /* "[opt_name1] opt_name2..." */
2240 /* "[opt_name1 #...] opt_name2... [#]" */
2241 /* "[opt_name1 [#...]] opt_name2... [#...]" */
2243 /* Where [ ] encloses an optional part, # means: has parameters and ... */
2244 /* means that there can be more than one occurrence of the previous thing. */
2246 /* opt_name can be followed by a 'new context' change prefixed with the */
2247 /* symbol >, as in opt1>c2 by eg. */
2249 /* This function returns as soon as one (or no) option has been parsed and */
2250 /* return the offset to the next option to parse. */
2252 /* In case of successful parsing, an new option is allocated and its */
2253 /* pointer returned. */
2254 /* ======================================================================== */
2256 opt_parse(char * s
, opt_t
** opt
)
2258 int opt_optional
= 0;
2259 int opt_multiple
= 0;
2260 int opt_count_matter
= 0;
2261 char opt_count_oper
= '\0';
2262 unsigned opt_count_mark
= 0;
2264 char opt_arg
[33] = { 0 };
2265 int opt_multiple_args
= 0;
2266 int opt_args_count_matter
= 0;
2267 char opt_args_count_oper
= '\0';
2268 unsigned opt_args_count_mark
= 0;
2269 int opt_optional_args
= 0;
2270 int opt_eval_first
= 0;
2284 memset(opt_arg
, '\0', 33);
2286 /* Strip the leading blanks. */
2287 /* """"""""""""""""""""""""" */
2291 if (*s
== '[') /* Start of an optional option. */
2296 s
= strtoken(s
, token
, sizeof(token
) - 1, "[^] \n\t.]", &pos
);
2298 return -1; /* Empty string. */
2300 /* Early EOS, only return success if the option is mandatory. */
2301 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2303 if (opt_optional
== 1)
2304 return -(s
- s_orig
- 1);
2306 /* Validate the option name */
2307 /* ALPHA+(ALPHANUM|_)* */
2308 /* """""""""""""""""""""""" */
2310 if (!isalpha(*p
) && *p
!= '*')
2311 return -(s
- s_orig
- 1); /* opt_name must start with a letter. */
2319 if (!isalnum(*p
) && *p
!= '_' && *p
!= '>')
2320 return -(s
- s_orig
- 1); /* opt_name must contain a letter, *
2321 * a number or a _ */
2326 opt_name
= xstrdup(token
+ 1); /* Ignore the first '*' in token. */
2328 opt_name
= xstrdup(token
);
2339 /* Check if it can appear multiple times by looking for the dots. */
2340 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2341 p
= strtoken(s
, token
, 3, "[.]", &pos
);
2344 if (strcmp(token
, "...") == 0)
2348 if (*s
== '<' || *s
== '=' || *s
== '>')
2353 n
= sscanf(s
+ 1, "%u%n", &value
, &offset
);
2356 opt_count_matter
= 1;
2357 opt_count_oper
= *s
;
2358 opt_count_mark
= value
;
2366 return -(s
- s_orig
- 1);
2372 /* Abort on extraneous ] if the option is mandatory. */
2373 /* """"""""""""""""""""""""""""""""""""""""""""""""" */
2375 return -(s
- s_orig
- 1);
2377 s
++; /* skip the ] */
2379 if (!*s
|| isblank(*s
))
2382 return -(s
- s_orig
- 1);
2385 /* A blank separates the option name and the argument tag. */
2386 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""" */
2398 n
= sscanf(s
, "[%32[^] .\t]%n%3[.]", opt_arg
, &pos
, dots
);
2399 if (pos
> 1 && *opt_arg
== '#') /* [# has been read. */
2402 opt_optional_args
= 1;
2404 opt_multiple_args
= 1; /* There were dots. */
2406 s
+= pos
+ !!(n
== 2) * 3; /* Skips the dots. */
2408 if (*s
== '<' || *s
== '=' || *s
== '>')
2413 n
= sscanf(s
+ 1, "%u%n", &value
, &offset
);
2416 opt_args_count_matter
= 1;
2417 opt_args_count_oper
= *s
;
2418 opt_args_count_mark
= value
;
2423 /* Optional arg tag must end with a ] */
2424 /* """""""""""""""""""""""""""""""""" */
2428 return -(s
- s_orig
- 1);
2431 s
++; /* Skip the ] */
2435 n
= sscanf(s
, "%32[^] .\t]%n%3[.]", opt_arg
, &pos
, dots
);
2436 if (pos
> 0 && *opt_arg
== '#') /* # has been read. */
2439 if (n
== 2) /* There were dots. */
2440 opt_multiple_args
= 1;
2442 s
+= pos
+ !!(n
== 2) * 3; /* Skip the dots */
2444 if (*s
== '<' || *s
== '=' || *s
== '>')
2449 n
= sscanf(s
+ 1, "%u%n", &value
, &offset
);
2452 opt_args_count_matter
= 1;
2453 opt_args_count_oper
= *s
;
2454 opt_args_count_mark
= value
;
2462 /* Abort on extraneous ] if the option is mandatory. */
2463 /* """"""""""""""""""""""""""""""""""""""""""""""""" */
2465 return -(s
- s_orig
- 1);
2467 s
++; /* skip the ] */
2469 /* Strip the following blanks. */
2470 /* """"""""""""""""""""""""""" */
2476 else if (opt_optional
== 0 && (!*s
|| isblank(*s
)))
2478 /* Strip the following blanks. */
2479 /* """"""""""""""""""""""""""" */
2485 else if (opt_args
== 0) /* # was not read it is possibly the start *
2486 * of another option. */
2489 return -(s
- s_orig
- 1);
2494 /* Strip the following blanks. */
2495 /* """"""""""""""""""""""""""" */
2501 if (*opt_name
== '>')
2502 fatal_internal("The option name is missing in %s.", opt_name
);
2504 count
= strchrcount(opt_name
, '>');
2507 char * tmp
= strchr(opt_name
, '>');
2508 next_ctx
= xstrdup(tmp
+ 1);
2512 fatal_internal("Only one occurrence of '>' is allowed in %s.", opt_name
);
2514 *opt
= xmalloc(sizeof(opt_t
));
2516 (*opt
)->name
= opt_name
;
2517 (*opt
)->optional
= opt_optional
;
2518 (*opt
)->multiple
= opt_multiple
;
2519 (*opt
)->opt_count_matter
= opt_count_matter
;
2520 (*opt
)->opt_count_oper
= opt_count_oper
;
2521 (*opt
)->opt_count_mark
= opt_count_mark
;
2522 (*opt
)->args
= opt_args
;
2523 (*opt
)->arg
= xstrdup(opt_arg
);
2524 (*opt
)->optional_args
= opt_optional_args
;
2525 (*opt
)->multiple_args
= opt_multiple_args
;
2526 (*opt
)->opt_args_count_matter
= opt_args_count_matter
;
2527 (*opt
)->opt_args_count_oper
= opt_args_count_oper
;
2528 (*opt
)->opt_args_count_mark
= opt_args_count_mark
;
2529 (*opt
)->eval_first
= opt_eval_first
;
2530 (*opt
)->next_ctx
= next_ctx
;
2531 (*opt
)->ctx_list
= ll_new();
2532 (*opt
)->constraints_list
= ll_new();
2533 (*opt
)->eval_before_list
= ll_new();
2534 (*opt
)->action
= NULL
;
2535 (*opt
)->params
= NULL
;
2536 (*opt
)->data
= NULL
;
2541 /* ==================================================================== */
2542 /* Try to initialize all the option in a given string */
2543 /* Each parsed option are put in a BST tree with its name as index. */
2545 /* On collision, the arguments only the signature are required to be */
2546 /* the same else this is considered as an error. Options can be used in */
2547 /* more than one context and can be optional in one and mandatory in */
2549 /* ==================================================================== */
2551 init_opts(char * spec
, ctx_t
* ctx
)
2553 opt_t
* opt
, *bst_opt
;
2559 if ((offset
= opt_parse(spec
, &opt
)) > 0)
2563 if ((node
= bst_find(opt
, &options_bst
, opt_compare
)) != NULL
)
2565 int same_next_ctx
= 0;
2567 bst_opt
= node
->key
; /* Node extracted from the BST. */
2569 if (bst_opt
->next_ctx
== NULL
&& opt
->next_ctx
== NULL
)
2571 else if (bst_opt
->next_ctx
== NULL
&& opt
->next_ctx
!= NULL
)
2573 else if (bst_opt
->next_ctx
!= NULL
&& opt
->next_ctx
== NULL
)
2576 same_next_ctx
= strcmp(bst_opt
->next_ctx
, opt
->next_ctx
) == 0;
2578 if (bst_opt
->optional_args
!= opt
->optional_args
2579 || bst_opt
->multiple_args
!= opt
->multiple_args
2580 || bst_opt
->args
!= opt
->args
|| !same_next_ctx
)
2582 fatal_internal("The option %s already exists with "
2583 "a different arguments signature.\n",
2587 /* The newly created opt is already present in options_bst. */
2588 /* We can remove it. */
2589 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2592 /* The new occurrence of the option option is legal */
2593 /* append the current context ptr in the list. */
2594 /* """""""""""""""""""""""""""""""""""""""""""""""" */
2595 ll_append(bst_opt
->ctx_list
, ctx
);
2597 /* Append the new option to the context's options list. */
2598 /* """""""""""""""""""""""""""""""""""""""""""""""""""" */
2599 ll_append(ctx
->opt_list
, bst_opt
);
2603 /* Initialize the option's context list with the current context. */
2604 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2605 ll_append(opt
->ctx_list
, ctx
);
2607 /* Append the new option to the context's options list. */
2608 /* """""""""""""""""""""""""""""""""""""""""""""""""""" */
2609 ll_append(ctx
->opt_list
, opt
);
2611 /* Insert the new option in the BST. */
2612 /* """"""""""""""""""""""""""""""""" */
2613 bst_search(opt
, &options_bst
, opt_compare
);
2618 char * s
= xstrndup(spec
, -offset
);
2619 printf("%s <---\nSyntax error at or before offset %d\n", s
, -offset
);
2629 /* ===================================================== */
2630 /* ctxopt initialization function, must be called first. */
2631 /* ===================================================== */
2633 ctxopt_init(char * prog_name
, char * init_flags
)
2637 contexts_bst
= NULL
;
2643 user_string
= xmalloc(8);
2644 user_string2
= xmalloc(8);
2646 char flag
[33], fname
[31], vname
[31];
2649 ctxopt_initialized
= 1;
2651 /* Initialize current_state.*/
2652 /* """""""""""""""""""""""" */
2653 cur_state
= xcalloc(sizeof(state_t
), 0);
2655 /* Initialize custom error function pointers to NULL. */
2656 /* """""""""""""""""""""""""""""""""""""""""""""""""" */
2657 err_functions
= xmalloc(CTXOPTERRSIZ
* sizeof(void *));
2658 for (n
= 0; n
< CTXOPTERRSIZ
; n
++)
2659 err_functions
[n
] = NULL
;
2661 /* Parse init_flags if any. */
2662 /* """""""""""""""""""""""" */
2663 while (*init_flags
&& (init_flags
= get_word(init_flags
, flag
, 32)))
2667 if (sscanf(flag
, "%30[^=]=%30[^=]", fname
, vname
) != 2)
2668 fatal_internal("Invalid flag assignment: %s.", flag
);
2670 if (strcmp(fname
, "stop_if_non_option") == 0)
2672 if (eval_yes(vname
, &invalid
))
2673 flags
.stop_if_non_option
= 1;
2675 flags
.stop_if_non_option
= 0;
2677 fatal_internal("Invalid flag value for %s: %s.", fname
, vname
);
2679 else if (strcmp(fname
, "allow_abbreviations") == 0)
2681 if (eval_yes(vname
, &invalid
))
2682 flags
.allow_abbreviations
= 1;
2684 flags
.allow_abbreviations
= 0;
2686 fatal_internal("Invalid flag value for %s: %s.", fname
, vname
);
2689 fatal_internal("Invalid flag name: %s.", fname
);
2693 /* Update current_state. */
2694 /* """"""""""""""""""""" */
2697 if (*prog_name
== '\0')
2698 cur_state
->prog_name
= xstrdup("program_name");
2699 else if ((ptr
= strrchr(prog_name
, '/')))
2700 cur_state
->prog_name
= xstrdup(ptr
+ 1);
2702 cur_state
->prog_name
= xstrdup(prog_name
);
2705 cur_state
->prog_name
= xstrdup("program_name");
2708 /* ========================================================================= */
2709 /* Utility function which create and register a par_t object in a BST */
2710 /* embedded in a context. */
2711 /* This object will have a name and a pointer to the option it refers to. */
2712 /* These object will be used to quickly find an option from a command */
2713 /* line parameter during the analysis phase. */
2715 /* IN : an option name. */
2716 /* IN : a string of command line parameters to associate to the option. */
2717 /* Returns : 1 is all was fine else 0. */
2718 /* ========================================================================= */
2720 opt_set_parms(char * opt_name
, char * par_str
)
2722 char * par_name
, *ctx_name
;
2723 char * tmp_par_str
, *end_tmp_par_str
;
2727 par_t
* par
, tmp_par
;
2728 int rc
= 1; /* return code */
2733 /* Look if the given option is defined. */
2734 /* """""""""""""""""""""""""""""""""""" */
2735 opt
= locate_opt(opt_name
);
2737 fatal_internal("Unknown option %s.", opt_name
);
2739 /* For each context using this option. */
2740 /* """"""""""""""""""""""""""""""""""" */
2741 list
= opt
->ctx_list
;
2744 while (lnode
!= NULL
)
2746 /* Locate the context in the contexts tree. */
2747 /* """""""""""""""""""""""""""""""""""""""" */
2748 ctx_name
= ((ctx_t
*)(lnode
->data
))->name
;
2750 ctx
= locate_ctx(ctx_name
);
2752 fatal_internal("Unknown context %s.", ctx_name
);
2755 void * par_bst
= ctx
->par_bst
;
2757 tmp_par_str
= xstrdup(par_str
);
2758 ltrim(tmp_par_str
, " \t");
2759 rtrim(tmp_par_str
, " \t", 0);
2760 par_name
= xstrtok_r(tmp_par_str
, " \t,", &end_tmp_par_str
);
2761 if (par_name
== NULL
)
2762 fatal_internal("Parameters are missing for option %s.", opt_name
);
2764 /* For each parameter given in par_str, creates a par_t object and */
2765 /* insert it the in the parameters BST of the context. */
2766 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2767 while (par_name
!= NULL
)
2769 tmp_par
.name
= par_name
;
2771 node
= bst_find(&tmp_par
, &par_bst
, par_compare
);
2774 fatal_internal("The parameter %s is already defined in context %s.",
2775 par_name
, ctx
->name
);
2780 par
= xmalloc(sizeof(par_t
));
2781 par
->name
= xstrdup(par_name
);
2782 par
->opt
= opt
; /* Link the option to this parameter */
2784 bst_search(par
, &par_bst
, par_compare
);
2786 par_name
= xstrtok_r(NULL
, " \t,", &end_tmp_par_str
);
2789 /* Update the value of the root of ctx->par_bst as it may have */
2790 /* been modified. */
2791 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2792 ctx
->par_bst
= par_bst
;
2796 lnode
= lnode
->next
;
2802 /* ==================================================================== */
2803 /* Create a new context instance. */
2804 /* IN ctx : a context pointer to allow this instance to */
2805 /* access the context fields */
2806 /* IN prev_ctx_inst : the context instance whose option leading to the */
2807 /* creation of this new context instance is part of */
2808 /* Returns : the new context. */
2809 /* ==================================================================== */
2811 new_ctx_inst(ctx_t
* ctx
, ctx_inst_t
* prev_ctx_inst
)
2814 opt_inst_t
* gen_opt_inst
;
2815 ctx_inst_t
* ctx_inst
;
2816 seen_opt_t
* seen_opt
;
2817 char * str
, *opt_name
;
2821 /* Keep a trace of the opt_inst which was at the origin of the creation */
2822 /* of this context instance. */
2823 /* This will serve during the evaluation of the option callbacks. */
2824 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2825 if (prev_ctx_inst
!= NULL
)
2827 gen_opt_inst
= (opt_inst_t
*)(prev_ctx_inst
->opt_inst_list
->tail
->data
);
2829 /* Update current_state. */
2830 /* """"""""""""""""""""" */
2831 cur_state
->opt_name
= gen_opt_inst
->opt
->name
;
2834 gen_opt_inst
= NULL
;
2836 /* Create and initialize the new context instance. */
2837 /* """"""""""""""""""""""""""""""""""""""""""""""" */
2838 ctx_inst
= xmalloc(sizeof(ctx_inst_t
));
2839 ctx_inst
->ctx
= ctx
;
2840 ctx_inst
->prev_ctx_inst
= prev_ctx_inst
;
2841 ctx_inst
->gen_opt_inst
= gen_opt_inst
;
2842 ctx_inst
->incomp_bst_list
= ll_new();
2843 ctx_inst
->opt_inst_list
= ll_new();
2844 ctx_inst
->seen_opt_bst
= NULL
;
2848 if (prev_ctx_inst
== NULL
)
2849 first_ctx_inst
= ctx_inst
;
2851 /* Initialize the occurrence counters of each opt allowed in the context. */
2852 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2853 node
= ctx
->opt_list
->head
;
2854 while (node
!= NULL
)
2857 opt
->occurrences
= 0;
2862 /* Initialize the BST containing the seen indicator for all the options */
2863 /* allowed in this context instance. */
2864 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2865 node
= ctx
->opt_list
->head
;
2866 while (node
!= NULL
)
2869 seen_opt
= xmalloc(sizeof(seen_opt_t
));
2870 seen_opt
->opt
= opt
;
2871 seen_opt
->par
= NULL
;
2874 bst_search(seen_opt
, &(ctx_inst
->seen_opt_bst
), seen_opt_compare
);
2879 /* Initialize the BST containing the incompatibles options. */
2880 /* Incompatibles option names are read from strings found in the list */
2881 /* incomp_list present in each instance of ctx_t. */
2882 /* These names are then used to search for the object of type seen_opt_t */
2883 /* which is already present in the seen_opt_bst of the context instance. */
2885 /* Once found the seen_opt_t object in inserted in the new BST */
2886 /* At the end the new BST in added to the list incomp_bst_list. */
2887 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2888 node
= ctx
->incomp_list
->head
;
2889 while (node
!= NULL
)
2892 seen_opt_t tmp_seen_opt
;
2894 str
= xstrdup(node
->data
);
2896 rtrim(str
, " \t", 0);
2897 opt_name
= strtok(str
, " \t"); /* Extract the first option name. */
2899 while (opt_name
!= NULL
) /* For each option name. */
2901 if ((opt
= locate_opt(opt_name
)) != NULL
)
2903 /* The option found is searched in the tree of potential */
2905 /* """"""""""""""""""""""""""""""""""""""""""""""""""""" */
2906 tmp_seen_opt
.opt
= opt
;
2908 bst_node
= bst_find(&tmp_seen_opt
, &(ctx_inst
->seen_opt_bst
),
2911 if (bst_node
!= NULL
)
2913 /* If found then it is added into the new BST tree. */
2914 /* """""""""""""""""""""""""""""""""""""""""""""""" */
2915 seen_opt
= bst_node
->key
;
2916 bst_search(seen_opt
, &bst
, seen_opt_compare
);
2919 /* Not found! That means that the option is unknown in this */
2920 /* context as all options has have a seen_opt structure in */
2922 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2923 fatal_internal("%s is not known in the context %s.", opt
->name
,
2927 fatal_internal("Unknown option %s.", opt_name
);
2929 opt_name
= strtok(NULL
, " \t");
2933 ll_append(ctx_inst
->incomp_bst_list
, bst
);
2941 /* ====================================================================== */
2942 /* Create a list formed by all the significant command line words */
2943 /* Words beginning or ending with { or } are split. Each of these */
2944 /* symbols will get their own place in the list. */
2946 /* the {...} part delimits a context, the { will not appear in the list */
2947 /* and the } will be replaced by a | in the resulting list (cmdline_list) */
2948 /* to facilitate the parsing phase. | must not be used by the end user. */
2950 /* IN nb_word : number of word to parse, this is typically argc-1 as the */
2951 /* program name is not considered. */
2952 /* IN words : is the array of strings constituting the command line to */
2954 /* Returns : 1 on success, 0 if a { or } is missing. */
2955 /* ====================================================================== */
2957 ctxopt_build_cmdline_list(int nb_words
, char ** words
)
2960 char * prev_word
= NULL
;
2964 ll_node_t
*node
, *start_node
;
2966 /* The analysis is divided into three passes, this is not optimal but */
2967 /* must be done only one time. Doing that we privilege readability. */
2969 /* In the following, SG is the ascii character 1d (dec 29) */
2971 /* The first pass creates the list, extract the leading an trailing */
2972 /* SG '{' and '}' of each word and give them their own place in the */
2975 /* The second pass transform the '{...}' blocks by a trailing SG */
2976 /* ({...} -> ...|) */
2978 /* The last pass remove the duplicated SG, check for SG, '{' or '}' in */
2979 /* the middle in the remaining list elements and recreate the pseudo */
2981 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2983 /* If the option list is not empty, clear it before going further. */
2984 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
2985 if (cmdline_list
!= NULL
)
2987 node
= cmdline_list
->head
;
2988 while (node
!= NULL
)
2991 ll_delete(cmdline_list
, node
);
2992 node
= cmdline_list
->head
;
2996 cmdline_list
= ll_new();
2998 start_node
= cmdline_list
->head
; /* In the following loop start_node will *
2999 * contain a pointer to the current *
3000 * word stripped from its leading *
3001 * sequence of {, }. */
3002 for (i
= 0; i
< nb_words
; i
++)
3004 size_t len
= strlen(words
[i
]);
3010 /* Replace each occurrence of the legal word {} by the characters */
3011 /* 0x02 and 0x03 to hide them from the following process. */
3012 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3013 while ((ptr
= strstr(str
, "{}")) != NULL
)
3015 *ptr
= 0x02; /* Arbitrary values unlikely. */
3016 *(ptr
+ 1) = 0x03; /* present in a word */
3019 if (len
> 1) /* The word contains at least 2 characters. */
3023 /* Interpret its beginning and look for the start of the real word. */
3024 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3025 while (start
<= len
- 1 && (str
[start
] == '{' || str
[start
] == '}'))
3027 ll_append(cmdline_list
, xstrndup(str
+ start
, 1));
3029 start_node
= cmdline_list
->tail
;
3033 if (str
[end
] == '{' || str
[end
] == '}')
3035 if (end
> 0 && str
[end
- 1] != '\\')
3037 ll_append(cmdline_list
, xstrndup(str
+ end
, 1));
3039 node
= cmdline_list
->tail
;
3041 while (str
[end
] == '{' || str
[end
] == '}')
3043 if (end
> start
&& str
[end
- 1] == '\\')
3046 ll_insert_before(cmdline_list
, node
, xstrndup(str
+ end
, 1));
3055 if (start_node
!= NULL
)
3056 ll_insert_after(cmdline_list
, start_node
,
3057 xstrndup(str
+ start
, end
- start
+ 1));
3059 ll_append(cmdline_list
, xstrndup(str
+ start
, end
- start
+ 1));
3060 start_node
= cmdline_list
->tail
;
3065 ll_append(cmdline_list
, xstrdup(str
));
3066 start_node
= cmdline_list
->tail
;
3072 node
= cmdline_list
->head
;
3075 while (node
!= NULL
)
3079 if (strcmp(word
, "{") == 0)
3081 ll_node_t
* old_node
= node
;
3085 ll_delete(cmdline_list
, old_node
);
3087 else if (strcmp(word
, "}") == 0)
3105 node
= cmdline_list
->head
;
3107 while (node
!= NULL
)
3111 /* Restore the original { and } characters forming the legal word {}. */
3112 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3113 while ((ptr
= strchr(word
, 0x02)) != NULL
)
3115 while ((ptr
= strchr(word
, 0x03)) != NULL
)
3118 /* Remove a SG if the previous element is SG. */
3119 /* """""""""""""""""""""""""""""""""""""""""" */
3120 if (strcmp(word
, "\x1d") == 0)
3122 if (prev_word
!= NULL
&& (strcmp(prev_word
, "\x1d") == 0))
3124 ll_node_t
* old_node
= node
;
3126 free(old_node
->data
);
3127 ll_delete(cmdline_list
, old_node
);
3130 else if (strcmp(word
, "-") == 0) /* A single - is a legal argument, not *
3131 * a parameter. Protect it. */
3134 node
->data
= xstrdup("\\-");
3137 prev_word
= node
->data
;
3141 /* Clean useless and SG at the beginning and end of list. */
3142 /* """""""""""""""""""""""""""""""""""""""""""""""""""""" */
3143 node
= cmdline_list
->head
;
3150 if (strcmp(word
, "\x1d") == 0)
3153 ll_delete(cmdline_list
, node
);
3156 node
= cmdline_list
->tail
;
3162 if (strcmp(word
, "\x1d") == 0)
3165 ll_delete(cmdline_list
, node
);
3171 /* ===================================================================== */
3172 /* Build and analyze the command line list and create the linked data */
3173 /* structures whose data will be evaluated later by ctxopt_evaluate. */
3174 /* This function identifies the following errors and creates an array of */
3175 /* The remaining unanalyzed arguments. */
3176 /* - detect missing arguments */
3177 /* - detect too many arguments */
3178 /* - detect unknown parameters in a context */
3179 /* - detect too many occurrences of a parameters in a context */
3180 /* - detect missing required arguments in a context */
3182 /* IN nb_word : number of word to parse, this is typically argc-1 as the */
3183 /* program name is not considered */
3184 /* IN words : is the array of strings constituting the command line to */
3186 /* OUT nb_rem_args : nb of remaining command line arguments if a -- */
3187 /* is present in the list. */
3188 /* OUT rem_args : array of remaining command line arguments if a -- */
3189 /* is present in the list. This array must be free by */
3190 /* The caller as it is allocated here. */
3191 /* ===================================================================== */
3193 ctxopt_analyze(int nb_words
, char ** words
, int * nb_rem_args
,
3196 char * ctxopt_debug_env
; /* Environment variable CTXOPT_DEBUG content. */
3197 int ctxopt_debug
; /* 1 if ctxopt_debug_env is set and not empty. *
3198 | 0 if ctxopt_debug_env is unset or empty. */
3203 ctx_inst_t
* ctx_inst
;
3204 opt_inst_t
* opt_inst
;
3207 int expect_par_or_arg
= 0;
3209 ll_node_t
* cli_node
;
3211 seen_opt_t
* bst_seen_opt
;
3217 if (!ctxopt_build_cmdline_list(nb_words
, words
))
3218 fatal_internal("The command line could not be parsed: "
3219 "missing '{' or '}' detected.");
3221 if (main_ctx
== NULL
)
3222 fatal_internal("At least one context must have been created.");
3224 /* Check that all options has an action and at least one parameter. */
3225 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3226 bst_walk(options_bst
, bst_check_opt_cb
);
3228 /* CTXOPT debug setting */
3229 /* """""""""""""""""""" */
3230 ctxopt_debug_env
= getenv("CTXOPT_DEBUG");
3231 if (ctxopt_debug_env
!= NULL
&& *ctxopt_debug_env
!= '\0')
3236 /* Create the first ctx_inst record. */
3237 /* """"""""""""""""""""""""""""""""" */
3240 ctx_inst_list
= ll_new();
3241 ctx_inst
= new_ctx_inst(ctx
, NULL
);
3242 ctx_inst
->par_name
= NULL
;
3244 /* Update current_state. */
3245 /* """"""""""""""""""""" */
3246 cur_state
->ctx_name
= ctx
->name
;
3248 ll_append(ctx_inst_list
, ctx_inst
);
3250 /* For each node in the command line. */
3251 /* """""""""""""""""""""""""""""""""" */
3252 cli_node
= cmdline_list
->head
;
3254 while (cli_node
!= NULL
)
3256 if (strcmp(cli_node
->data
, "--") == 0)
3257 break; /* No new parameter will be analyzed after this point. */
3259 par_name
= cli_node
->data
;
3261 /* Replace a leading -- by a single - */
3262 /* """""""""""""""""""""""""""""""""" */
3263 if (strncmp(cli_node
->data
, "--", 2) == 0)
3264 par_name
+= 1; /* Ignore the first dash */
3266 if (strcmp(par_name
, "\x1d") == 0)
3268 check_for_missing_mandatory_opt(ctx_inst
, (char *)(cli_node
->prev
->data
));
3269 check_for_occurrences_issues(ctx_inst
);
3271 /* Forced backtracking to the previous context instance. */
3272 /* """"""""""""""""""""""""""""""""""""""""""""""""""""" */
3273 if (ctx_inst
->prev_ctx_inst
!= NULL
)
3275 ctx_inst
= ctx_inst
->prev_ctx_inst
;
3276 ctx
= ctx_inst
->ctx
;
3278 /* Update current_states. */
3279 /* """"""""""""""""""""" */
3280 cur_state
->ctx_name
= ctx
->name
;
3281 cur_state
->ctx_par_name
= ctx_inst
->par_name
;
3285 "CTXOPT_DEBUG: Context forced backtrack, "
3286 "new current context: %s.\n",
3291 /* Update current_state. */
3292 /* """"""""""""""""""""" */
3293 cur_state
->ctx_par_name
= NULL
;
3296 else if (expect_par
&& *par_name
== '-')
3301 /* Update current_state. */
3302 /* """"""""""""""""""""" */
3303 cur_state
->cur_opt_par_name
= par_name
;
3304 cur_state
->ctx_name
= ctx
->name
;
3305 cur_state
->ctx_par_name
= ctx_inst
->par_name
;
3308 fprintf(stderr
, "CTXOPT_DEBUG: Parameter: %s. Current context: %s.\n",
3309 par_name
, cur_state
->ctx_name
);
3311 /* An expected parameter has been seen. */
3312 /* """""""""""""""""""""""""""""""""""" */
3313 if ((par
= locate_par(par_name
, ctx
)) == NULL
)
3318 /* Look if this parameter is an unique abbreviation of a longer */
3319 /* parameter. If this is the case then just replace it with its */
3320 /* full length version and try again. */
3321 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3322 if (flags
.allow_abbreviations
)
3323 if ((word
= abbrev_expand(par_name
, ctx
)) != NULL
)
3325 cli_node
->data
= word
;
3329 /* Try to find a prefix which is a valid parameter in this context */
3330 /* If found, split the cli_node in two to build a new parameter */
3331 /* node and followed by a node containing the remaining string */
3332 /* If the new parameter corresponds to an option not taking */
3333 /* argument then prefix the remaining string whit a dash as it may */
3334 /* contain a new parameter. */
3335 /* The new parameter will be re-evaluated in the next iteration of */
3337 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""*/
3338 prefix
= look_for_valid_prefix_in_word(par_name
, ctx
, &pos
, &popt
);
3339 if (prefix
!= NULL
&& pos
!= 0)
3343 "CTXOPT_DEBUG: Found a valid parameter "
3344 "as a prefix of %s: %s.\n",
3347 cli_node
->data
= prefix
; /* prefix contains le name of a valid *
3348 | parameter in this context. */
3352 /* The parameter may be followed by arguments. */
3353 /* ''''''''''''''''''''''''''''''''''''''''''' */
3354 if (*(par_name
+ pos
) == '-')
3356 word
= xstrdup("\\"); /* Protect the '-' */
3357 word
= strappend(word
, par_name
+ pos
, (char *)0);
3360 word
= xstrdup(par_name
+ pos
);
3364 /* The parameter does not take arguments, the */
3365 /* following word must be a parameter or nothing */
3366 /* hence prefix it with a dash. */
3367 /* ''''''''''''''''''''''''''''''''''''''''''''' */
3368 word
= xstrdup("-");
3369 word
= strappend(word
, par_name
+ pos
, (char *)0);
3372 /* Insert it after the current node in the list. */
3373 /* """"""""""""""""""""""""""""""""""""""""""""" */
3374 ll_insert_after(cmdline_list
, cli_node
, word
);
3376 continue; /* loop */
3380 check_for_missing_mandatory_opt(ctx_inst
, par_name
);
3381 check_for_occurrences_issues(ctx_inst
);
3383 if (ctx_inst
->prev_ctx_inst
== NULL
)
3385 char * errmsg
= xstrdup("");
3387 /* Update current_state. */
3388 /* """"""""""""""""""""" */
3389 cur_state
->ctx_par_name
= NULL
;
3391 *user_string
= '\0';
3392 *user_string2
= '\0';
3394 user_string
= strappend(user_string
, par_name
, (char *)0);
3396 bst_walk(contexts_bst
, bst_match_par_cb
);
3398 if (*user_string2
!= '\0')
3402 "\nThis parameter is only valid in one of the following "
3405 "\n\nSwitch to one of them first using the appropriate "
3406 "parameter, see below.\n",
3410 fatal(CTXOPTUNKPAR
, errmsg
);
3414 /* Tries to backtrack and analyse the same parameter in the */
3415 /* previous context. */
3416 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3417 ctx_inst
= ctx_inst
->prev_ctx_inst
;
3418 ctx
= ctx_inst
->ctx
;
3422 "CTXOPT_DEBUG: Context backtrack, "
3423 "new current context: %s.\n",
3426 /* Update current_state. */
3427 /* """"""""""""""""""""" */
3428 cur_state
->ctx_name
= ctx
->name
;
3429 cur_state
->ctx_par_name
= ctx_inst
->par_name
;
3431 cli_node
= cli_node
->prev
;
3437 seen_opt_t seen_opt
;
3439 /* The parameter is valid in the context, create a opt_inst and */
3440 /* append it to the ctx_inst list options list. */
3441 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3446 opt_inst
= xmalloc(sizeof(opt_inst_t
));
3447 opt_inst
->opt
= opt
;
3448 opt_inst
->par
= par_name
;
3449 opt_inst
->values_list
= ll_new();
3450 opt_inst
->next_ctx_inst
= NULL
;
3452 /* Update current_state. */
3453 /* """"""""""""""""""""" */
3454 cur_state
->cur_opt_params
= opt
->params
;
3456 /* Priority option are inserted at the start of the opt_inst list */
3457 /* but their order of appearance in the context definition must */
3458 /* be preserver so each new priority option will be placed after */
3459 /* the previous ones at the start of the opt_inst list. */
3460 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3461 if (!opt
->eval_first
)
3463 /* Look if we have a registered dependency in the order of the */
3464 /* evaluation of two options. */
3465 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3466 if (opt
->eval_before_list
->len
> 0)
3468 ll_t
* list
= ctx_inst
->opt_inst_list
;
3469 ll_node_t
* opt_inst_node
;
3471 ll_t
* before_list
= opt
->eval_before_list
;
3472 ll_node_t
* before_node
= before_list
->head
;
3474 ll_node_t
* target_node
= NULL
; /* If not NULL, the new node *
3475 | will be inserted before it. */
3477 /* For each entry in eval_before_list, try to find if it */
3478 /* refers to an option already entered in the context. If this */
3479 /* is the case, insert it just before it instead of putting it */
3481 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3482 while (before_node
!= NULL
)
3484 opt_inst_node
= list
->head
;
3486 while (opt_inst_node
!= target_node
)
3488 opt_t
* tmp_opt
= (((opt_inst_t
*)opt_inst_node
->data
))->opt
;
3490 /* We have found an option mentioned if the before_list */
3491 /* of the option we want to add. We can stop searching. */
3492 /* """"""""""""""""""""""""""""""""""""""""""""""""""""" */
3493 if (strcmp(tmp_opt
->name
, ((opt_t
*)before_node
->data
)->name
))
3494 opt_inst_node
= opt_inst_node
->next
;
3496 target_node
= opt_inst_node
; /* Set the target node. */
3499 before_node
= before_node
->next
;
3502 /* Insert or append ? */
3503 /* """""""""""""""""" */
3504 if (target_node
!= NULL
)
3505 ll_insert_before(ctx_inst
->opt_inst_list
, target_node
, opt_inst
);
3507 ll_append(ctx_inst
->opt_inst_list
, opt_inst
);
3510 ll_append(ctx_inst
->opt_inst_list
, opt_inst
);
3514 ll_node_t
* opt_inst_node
= ctx_inst
->opt_inst_list
->head
;
3515 opt_inst_t
* tmp_opt_inst
;
3517 while (opt_inst_node
!= NULL
)
3519 tmp_opt_inst
= opt_inst_node
->data
;
3520 if (!tmp_opt_inst
->opt
->eval_first
)
3522 ll_insert_before(ctx_inst
->opt_inst_list
, opt_inst_node
,
3527 opt_inst_node
= opt_inst_node
->next
;
3529 if (opt_inst_node
== NULL
)
3530 ll_append(ctx_inst
->opt_inst_list
, opt_inst
);
3533 /* Check if an option was already seen in the */
3534 /* current context instance. */
3535 /* """""""""""""""""""""""""""""""""""""""""" */
3538 bst_node
= bst_find(&seen_opt
, &(ctx_inst
->seen_opt_bst
),
3541 /* bst_node cannot be NULL here. */
3543 bst_seen_opt
= (seen_opt_t
*)(bst_node
->key
);
3545 if (!opt
->multiple
&& bst_seen_opt
->seen
== 1)
3546 fatal(CTXOPTDUPOPT
, NULL
);
3548 /* Check if this option is compatible with the options already */
3549 /* seen in this context instance. */
3550 /* Look if the option is present in one on the BST present in */
3551 /* the incomp_bst_list of the context instance. */
3552 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3553 node
= ctx_inst
->incomp_bst_list
->head
;
3554 while (node
!= NULL
)
3559 /* There can only have one seen_opt object in the BST tree was */
3560 /* already seen, try to locate it, the result will be put in */
3561 /* user_object by the bst_seen_opt_seen_cb function. */
3562 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3563 bst_walk(bst
, bst_seen_opt_seen_cb
);
3565 /* If it is the case, look if the current option is also */
3567 /* """"""""""""""""""""""""""""""""""""""""""""""""""""" */
3568 if (user_object
!= NULL
)
3570 bst_node
= bst_find(bst_seen_opt
, &bst
, seen_opt_compare
);
3572 if (bst_node
!= NULL
)
3574 bst_seen_opt
= (seen_opt_t
*)(bst_node
->key
);
3575 if (bst_seen_opt
->seen
== 0)
3576 fatal(CTXOPTINCOPT
, (char *)user_object
);
3583 /* Mark this option as seen in the current context instance. */
3584 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3585 bst_seen_opt
->seen
= 1;
3586 free(bst_seen_opt
->par
);
3587 bst_seen_opt
->par
= xstrdup(par_name
);
3589 /* If this option leads to a next context, create a new ctx_inst */
3590 /* and switch to it for the analyse of the future parameter. */
3591 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3592 if (opt
->next_ctx
!= NULL
)
3594 ctx
= locate_ctx(opt
->next_ctx
);
3597 fatal_internal("Unknown context %s.", opt
->next_ctx
);
3599 opt_inst
->next_ctx_inst
= ctx_inst
= new_ctx_inst(ctx
, ctx_inst
);
3600 ctx_inst
->par_name
= xstrdup(par_name
);
3602 ll_append(ctx_inst_list
, ctx_inst
);
3606 "CTXOPT_DEBUG: Context change, "
3607 "new current context: %s.\n",
3611 /* Look is we must expect some arguments. */
3612 /* """""""""""""""""""""""""""""""""""""" */
3613 expect_par_or_arg
= 0;
3618 expect_par
= 1; /* Parameter doesn't accept any argument. */
3621 if (!opt
->optional_args
)
3622 expect_arg
= 1; /* Parameter has mandatory arguments. */
3624 expect_par_or_arg
= 1; /* Parameter has optional arguments. */
3628 else if (expect_par
&& *par_name
!= '-')
3630 ll_node_t
* n
= cli_node
->next
;
3632 if (!flags
.stop_if_non_option
)
3633 /* Look if potential arguments must still be analyzed until the */
3634 /* end of the context/command line part to analyze/command line. */
3635 /* If this is the case we have met an extra argument. */
3636 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3639 if (strcmp(n
->data
, "--") == 0 || strcmp(n
->data
, "\x1d") == 0)
3640 fatal(CTXOPTUNXARG
, NULL
);
3642 if (*(char *)(n
->data
) == '-')
3643 fatal(CTXOPTUNXARG
, NULL
);
3648 break; /* An unexpected non parameter was seen, if no Potential *
3649 | arguments remain in the command line or *
3650 | flags.stop_if_non_option is set, assume that it is is *
3651 | the first of the non arguments and stop the command *
3654 else if (expect_arg
&& *par_name
!= '-')
3656 ll_node_t
* cstr_node
;
3657 constraint_t
* cstr
;
3660 fprintf(stderr
, "CTXOPT_DEBUG: Argument: %s.\n", par_name
);
3662 /* Check if the arguments of the option respects */
3663 /* the attached constraints if any. */
3664 /* """"""""""""""""""""""""""""""""""""""""""""" */
3665 cstr_node
= opt
->constraints_list
->head
;
3666 while (cstr_node
!= NULL
)
3668 cstr
= cstr_node
->data
;
3669 if (!cstr
->constraint(cstr
->nb_args
, cstr
->args
, par_name
,
3670 cur_state
->cur_opt_par_name
))
3672 fputs("\n", stderr
);
3673 ctxopt_ctx_disp_usage(cur_state
->ctx_name
, exit_after
);
3676 cstr_node
= cstr_node
->next
;
3679 /* If the argument is valid, store it. */
3680 /* """"""""""""""""""""""""""""""""""" */
3681 if (*par_name
== '\\' && *(par_name
+ 1) == '-')
3682 ll_append(opt_inst
->values_list
, par_name
+ 1);
3684 ll_append(opt_inst
->values_list
, par_name
);
3688 expect_par_or_arg
= 0;
3690 if (opt
->multiple_args
)
3691 expect_par_or_arg
= 1;
3693 expect_par
= 1; /* Parameter takes only one argument. */
3695 else if (expect_arg
&& *par_name
== '-')
3696 fatal(CTXOPTMISARG
, NULL
);
3697 else if (expect_par_or_arg
)
3701 expect_par_or_arg
= 0;
3703 if (*par_name
!= '-')
3704 expect_arg
= 1; /* Consider this word as an argument and retry. */
3706 expect_par
= 1; /* Consider this word as a parameter and retry. */
3708 cli_node
= cli_node
->prev
;
3711 cli_node
= cli_node
->next
;
3714 if (cmdline_list
->len
> 0 && *par_name
== '-')
3716 if (expect_arg
&& !opt
->optional_args
)
3717 fatal(CTXOPTMISARG
, NULL
);
3720 /* Look if a context_instance has unseen mandatory options. */
3721 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3722 node
= ctx_inst_list
->head
;
3723 while (node
!= NULL
)
3725 ctx_inst
= node
->data
;
3727 /* Update current_state. */
3728 /* """"""""""""""""""""" */
3729 cur_state
->ctx_name
= ctx_inst
->ctx
->name
;
3730 cur_state
->ctx_par_name
= ctx_inst
->par_name
;
3732 check_for_missing_mandatory_opt(ctx_inst
, par_name
);
3733 check_for_occurrences_issues(ctx_inst
);
3738 /* Allocate the array containing the remaining not analyzed */
3739 /* command line arguments. */
3740 /* NOTE: The strings in the array are just pointer to the */
3741 /* data of the generating list and must not be freed. */
3742 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3743 if (cli_node
!= NULL
)
3745 if (strcmp((char *)cli_node
->data
, "--") == 0)
3746 /* The special parameter -- was encountered, the -- argument is not */
3747 /* put in the remaining arguments. */
3748 /* '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' */
3749 ll_strarray(cmdline_list
, cli_node
->next
, nb_rem_args
, rem_args
);
3751 /* A non parameter was encountered when a parameter was expected. We */
3752 /* assume that the evaluation of the remaining command line argument */
3753 /* are not the responsibility of the users code. */
3754 /* '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' */
3755 ll_strarray(cmdline_list
, cli_node
, nb_rem_args
, rem_args
);
3760 *rem_args
= xmalloc(sizeof(char *));
3761 (*rem_args
)[0] = NULL
;
3765 /* ==================================================== */
3766 /* Free ctxopt memory used for its internal structures. */
3767 /* ==================================================== */
3769 ctxopt_free_memory(void)
3771 ll_destroy(cmdline_list
, free
);
3772 ll_destroy(ctx_inst_list
, ctx_inst_free
);
3773 bst_destroy(options_bst
, opt_free
);
3774 bst_destroy(contexts_bst
, ctx_free
);
3777 /* ==================================================================== */
3778 /* Parse the options data structures and launches the callback function */
3779 /* attached to each options instances. */
3780 /* This calls a recursive function which proceeds context per context. */
3781 /* ==================================================================== */
3783 ctxopt_evaluate(void)
3785 evaluate_ctx_inst(first_ctx_inst
);
3788 /* =================================================================== */
3789 /* Recursive function called by ctxopt_evaluate to process the list of */
3790 /* the opt_inst present in a ctx_inst and attempt to evaluate the */
3791 /* action attached to the context and its option instances. */
3792 /* =================================================================== */
3794 evaluate_ctx_inst(ctx_inst_t
* ctx_inst
)
3796 opt_inst_t
* opt_inst
;
3799 ll_node_t
* opt_inst_node
;
3803 if (ctx_inst
== NULL
)
3806 ctx
= ctx_inst
->ctx
;
3808 /* Do not evaluate the action attached to this context is there is no */
3809 /* option to evaluate. */
3810 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3811 opt_inst_node
= ctx_inst
->opt_inst_list
->head
;
3812 if (opt_inst_node
== NULL
)
3815 /* Call the entering action attached to this context if any. */
3816 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3817 if (ctx
->action
!= NULL
)
3819 if (ctx_inst
->prev_ctx_inst
!= NULL
)
3820 ctx
->action(ctx
->name
, entering
, ctx_inst
->prev_ctx_inst
->ctx
->name
,
3821 ctx
->nb_data
, ctx
->data
);
3823 ctx
->action(ctx
->name
, entering
, NULL
, ctx
->nb_data
, ctx
->data
);
3826 /* For each instance of options. */
3827 /* """"""""""""""""""""""""""""" */
3828 while (opt_inst_node
!= NULL
)
3830 opt_inst
= (opt_inst_t
*)(opt_inst_node
->data
);
3831 ll_strarray(opt_inst
->values_list
, opt_inst
->values_list
->head
, &nb_args
,
3833 opt
= opt_inst
->opt
;
3835 /* Launch the attached action if any. */
3836 /* """""""""""""""""""""""""""""""""" */
3837 if (opt
->action
!= NULL
)
3838 opt
->action(ctx
->name
, opt
->name
, opt_inst
->par
, nb_args
, args
,
3839 opt
->nb_data
, opt
->data
, ctx
->nb_data
, ctx
->data
);
3841 if (opt_inst
->next_ctx_inst
!= NULL
)
3842 evaluate_ctx_inst(opt_inst
->next_ctx_inst
);
3847 opt_inst_node
= opt_inst_node
->next
;
3850 /* Call the exiting action attached to this context if any. */
3851 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""" */
3852 if (ctx
->action
!= NULL
)
3854 if (ctx_inst
->prev_ctx_inst
!= NULL
)
3855 ctx
->action(ctx
->name
, exiting
, ctx_inst
->prev_ctx_inst
->ctx
->name
,
3856 ctx
->nb_data
, ctx
->data
);
3858 ctx
->action(ctx
->name
, exiting
, NULL
, ctx
->nb_data
, ctx
->data
);
3862 /* ============================================================ */
3863 /* Create and initializes a new context. */
3864 /* - allocate space. */
3866 /* - initialize its option with a few of their characteristics. */
3867 /* ============================================================ */
3869 ctxopt_new_ctx(char * name
, char * opts_specs
)
3874 if (!ctxopt_initialized
)
3875 fatal_internal("Please call ctxopt_init first.");
3877 ctx
= xmalloc(sizeof(ctx_t
));
3879 /* Validates the context name: */
3880 /* ALPHA+(ALPHANUM|_)* */
3881 /* """"""""""""""""""""""""""" */
3884 fatal_internal("A context name must start with a letter: %s.", name
);
3889 if (!isalnum(*p
) && *p
!= '_')
3890 fatal_internal("A context name must only contain letters, "
3891 "numbers or '_': %s.",
3896 ctx
->name
= xstrdup(name
);
3897 ctx
->opt_list
= ll_new(); /* List of options legit in this context. */
3898 ctx
->incomp_list
= ll_new(); /* List of incompatible options strings. */
3899 ctx
->par_bst
= NULL
;
3903 /* The first created context is the main one. */
3904 /* """""""""""""""""""""""""""""""""""""""""" */
3905 if (contexts_bst
== NULL
)
3909 cur_state
->ctx_name
= ctx
->name
;
3912 if (init_opts(opts_specs
, ctx
) == 0)
3914 if (bst_find(ctx
, &contexts_bst
, ctx_compare
) != NULL
)
3915 fatal_internal("The context %s already exists.", name
);
3917 bst_search(ctx
, &contexts_bst
, ctx_compare
);
3920 /* ==================================================== */
3921 /* Display a usage screen limited to a specific context */
3922 /* IN: the context name. */
3923 /* IN: what to do after (continue or exit the program) */
3924 /* possible values: continue_after, exit_after. */
3925 /* ==================================================== */
3927 ctxopt_ctx_disp_usage(char * ctx_name
, usage_behaviour action
)
3932 int has_optional
= 0;
3933 int has_ellipsis
= 0;
3935 int has_generic_arg
= 0;
3936 int has_ctx_change
= 0;
3937 int has_early_eval
= 0;
3939 ctx
= locate_ctx(ctx_name
);
3941 fatal_internal("Unknown context %s.", ctx_name
);
3943 if (cur_state
->ctx_par_name
== NULL
)
3944 printf("\nSynopsis:\n%s \\\n", cur_state
->prog_name
);
3946 printf("\nSynopsis for the context introduced by %s:\n",
3947 cur_state
->ctx_par_name
);
3949 list
= ctx
->opt_list
;
3950 print_options(list
, &has_optional
, &has_ellipsis
, &has_rule
, &has_generic_arg
,
3951 &has_ctx_change
, &has_early_eval
);
3953 print_explanations(has_early_eval
, has_ctx_change
, has_generic_arg
,
3954 has_optional
, has_ellipsis
, has_rule
);
3956 if (action
== exit_after
)
3960 /* =================================================== */
3961 /* Display a full usage screen about all contexts. */
3962 /* IN: what to do after (continue or exit the program) */
3963 /* possible values: continue_after, exit_after. */
3964 /* =================================================== */
3966 ctxopt_disp_usage(usage_behaviour action
)
3969 int has_optional
= 0;
3970 int has_ellipsis
= 0;
3972 int has_generic_arg
= 0;
3973 int has_ctx_change
= 0;
3974 int has_early_eval
= 0;
3976 if (main_ctx
== NULL
)
3977 fatal_internal("At least one context must have been created.");
3979 /* Usage for the first context. */
3980 /* """""""""""""""""""""""""""" */
3981 printf("\nAllowed options in the base context:\n");
3982 list
= main_ctx
->opt_list
;
3983 print_options(list
, &has_optional
, &has_ellipsis
, &has_rule
, &has_generic_arg
,
3984 &has_ctx_change
, &has_early_eval
);
3986 /* Usage for the other contexts. */
3987 /* """"""""""""""""""""""""""""" */
3988 bst_walk(contexts_bst
, bst_print_ctx_cb
);
3990 /* Contextual syntactic explanations. */
3991 /* """""""""""""""""""""""""""""""""" */
3992 print_explanations(has_early_eval
, has_ctx_change
, has_generic_arg
,
3993 has_optional
, has_ellipsis
, has_rule
);
3995 if (action
== exit_after
)
3999 /* *********************************** */
4000 /* Built-in constraint check functions */
4001 /* *********************************** */
4003 /* ============================================================= */
4004 /* This constraint checks if each arguments respects a format as */
4005 /* defined for the scanf function. */
4006 /* return 1 if yes and 0 if no. */
4007 /* ============================================================= */
4009 ctxopt_format_constraint(int nb_args
, char ** args
, char * value
, char * par
)
4018 fatal_internal("Format constraint, invalid number of parameters.");
4020 if (strlen(value
) > 255)
4023 format
= xstrdup(args
[0]);
4024 format
= strappend(format
, "%c", (char *)0);
4026 rc
= sscanf(value
, format
, x
, &y
);
4029 "The argument %s of %s does not respect the imposed format %s.",
4030 value
, par
, args
[0]);
4037 /* ================================================================== */
4038 /* This constraint checks if each arguments of the option instance is */
4039 /* between a minimum and a maximum (inclusive). */
4040 /* return 1 if yes and 0 if no. */
4041 /* ================================================================== */
4043 ctxopt_re_constraint(int nb_args
, char ** args
, char * value
, char * par
)
4049 "Regular expression constraint, invalid number of parameters.");
4051 if (regcomp(&re
, args
[0], REG_EXTENDED
) != 0)
4052 fatal_internal("Invalid regular expression %s.", args
[0]);
4054 if (regexec(&re
, value
, (size_t)0, NULL
, 0) != 0)
4057 "The argument %s of %s doesn't match the constraining "
4058 "regular expression %s.",
4059 value
, par
, args
[0]);
4068 /* ================================================================== */
4069 /* This constraint checks if each arguments of the option instance is */
4070 /* between a minimum and a maximum (inclusive). */
4071 /* return 1 if yes and 0 if no. */
4072 /* ================================================================== */
4074 ctxopt_range_constraint(int nb_args
, char ** args
, char * value
, char * par
)
4085 fatal_internal("Range constraint, invalid number of parameters.");
4087 if (strcmp(args
[0], ".") == 0)
4090 n
= sscanf(args
[0], "%ld%c", &min
, &c
);
4092 if (!max_only
&& n
!= 1)
4093 fatal_internal("Range constraint, min: invalid parameters.");
4095 if (strcmp(args
[1], ".") == 0)
4098 n
= sscanf(args
[1], "%ld%c", &max
, &c
);
4100 if (!min_only
&& n
!= 1)
4101 fatal_internal("Range constraint, max: invalid parameters.");
4103 if (min_only
&& max_only
)
4104 fatal_internal("Range constraint, invalid parameters.");
4107 v
= strtol(value
, &ptr
, 10);
4108 if (errno
|| ptr
== value
)
4116 "The argument %ld of %s is not greater than or equal to %ld.", v
,
4128 "The argument %ld of %s is not less than or equal to %ld.", v
,
4135 else if (v
< min
|| v
> max
)
4137 fprintf(stderr
, "The argument %ld of %s is not between %ld and %ld.", v
,
4142 return 1; /* check passed */
4145 /* =============================================================== */
4146 /* This function provides a way to set the behaviour of a context. */
4147 /* =============================================================== */
4149 ctxopt_add_global_settings(settings s
, ...)
4156 case error_functions
:
4158 typedef void fn(errors e
, state_t
* state
);
4160 void (*function
)(errors e
, state_t
* state
);
4163 e
= va_arg(args
, errors
);
4164 function
= va_arg(args
, fn
*);
4165 err_functions
[e
] = function
;
4175 /* ================================================================ */
4176 /* This function provides a way to set the behaviour of an option. */
4177 /* It can take a variable number of arguments according to its */
4178 /* first argument: */
4180 /* o a string containing an option name and all its possible */
4181 /* parameters separates by spaces, tabs or commas (char *) */
4182 /* (e.g: "help -h -help"). */
4184 /* o a string containing an option name. */
4185 /* o a pointer to a function which will be called at evaluation */
4187 /* - constraints: */
4188 /* o a string containing an option name. */
4189 /* o a pointer to a function to check if an argument is valid. */
4190 /* o a strings containing the arguments to this function. */
4191 /* ================================================================ */
4193 ctxopt_add_opt_settings(settings s
, ...)
4203 /* This part associates some command line parameters to an option. */
4204 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
4210 /* The second argument must be a string containing: */
4211 /* - The name of an existing option. */
4212 /* - a list of parameters with a leading dash (-). */
4213 /* """""""""""""""""""""""""""""""""""""""""""""""" */
4214 ptr
= va_arg(args
, char *);
4217 if (opt_name
!= NULL
)
4219 if ((opt
= locate_opt(opt_name
)) != NULL
)
4221 ptr
= va_arg(args
, char *);
4224 if (!opt_set_parms(opt_name
, params
))
4226 "Duplicated parameters or bad settings for the option %s.",
4230 fatal_internal("Unknown option %s.", opt_name
);
4234 "ctxopt_opt_add_settings: parameters: not enough arguments.");
4236 /* Here opt is a known option. */
4237 /* """"""""""""""""""""""""""" */
4238 if (opt
->params
!= NULL
)
4239 fatal_internal("Parameters are already set for %s.", opt_name
);
4243 size_t l
= strlen(params
);
4245 opt
->params
= xstrdup(params
);
4246 while ((n
= strcspn(opt
->params
, " \t")) < l
)
4247 opt
->params
[n
] = '|';
4253 /* This part associates a callback function to an option. */
4254 /* This function will be called when an instance of an option */
4256 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
4263 /* The second argument must be the name of an existing option. */
4264 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
4265 ptr
= va_arg(args
, char *);
4267 if ((opt
= locate_opt(ptr
)) != NULL
)
4269 typedef void fn(char *, char *, char *, int, char **, int, void *, int,
4272 /* The third argument must be the callback function. */
4273 /* """"""""""""""""""""""""""""""""""""""""""""""""" */
4274 function
= va_arg(args
, fn
*);
4275 opt
->action
= function
;
4277 /* The fourth argument must be a pointer to an user's defined */
4278 /* variable or structure that the previous function can manage. */
4279 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
4280 while ((data
= va_arg(args
, void *)) != NULL
)
4283 opt
->data
= xrealloc(opt
->data
, nb_data
* sizeof(void *));
4284 opt
->data
[nb_data
- 1] = data
;
4286 opt
->nb_data
= nb_data
;
4289 fatal_internal("Unknown option %s.", ptr
);
4293 /* This part associates a list of functions to control some */
4294 /* characteristics of the arguments of an option. */
4295 /* Each function will be called in order and must return 1 */
4296 /* to validate the arguments. */
4297 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""" */
4301 constraint_t
* cstr
;
4304 /* The second argument must be a string. */
4305 /* """"""""""""""""""""""""""""""""""""" */
4306 ptr
= va_arg(args
, char *);
4308 if ((opt
= locate_opt(ptr
)) != NULL
)
4310 typedef int fn(int, char **, char *);
4312 /* The third argument must be a function. */
4313 /* """""""""""""""""""""""""""""""""""""" */
4314 function
= va_arg(args
, fn
*);
4316 cstr
= xmalloc(sizeof(constraint_t
));
4317 cstr
->constraint
= function
;
4319 /* The fourth argument must be a string containing the argument of */
4320 /* The previous function separated by spaces or tabs. */
4321 /* Theses arguments will be passed to the previous function */
4322 /* max: 32 argument! */
4323 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
4324 value
= xstrdup(va_arg(args
, char *));
4326 cstr
->to_free
= value
;
4327 cstr
->args
= xcalloc(sizeof(char *), 32);
4328 cstr
->nb_args
= str2argv(value
, cstr
->args
, 32);
4329 ll_append(opt
->constraints_list
, cstr
);
4332 fatal_internal("Unknown option %s.", ptr
);
4336 /* This part allows to indicate that an option must be evaluated */
4337 /* after a list of other options. */
4338 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
4344 /* The second argument must be a string. */
4345 /* """"""""""""""""""""""""""""""""""""" */
4346 ptr
= va_arg(args
, char *);
4348 if ((opt
= locate_opt(ptr
)) != NULL
)
4354 ptr
= va_arg(args
, char *);
4358 rtrim(str
, " \t", 0);
4360 /* Feed the list of options to be evaluated after the given option. */
4361 /* This list will contain pointers to options. */
4362 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
4363 opt_name
= xstrtok_r(str
, " \t,", &end_str
);
4364 if (opt_name
!= NULL
)
4366 if ((opt_before
= locate_opt(opt_name
)) != NULL
)
4368 ll_append(opt
->eval_before_list
, opt_before
);
4369 while ((opt_name
= xstrtok_r(NULL
, " \t,", &end_str
)) != NULL
)
4371 if ((opt_before
= locate_opt(opt_name
)) != NULL
)
4372 ll_append(opt
->eval_before_list
, opt_before
);
4374 fatal_internal("Unknown option %s.", opt_name
);
4378 fatal_internal("Unknown option %s.", opt_name
);
4381 fatal_internal("Not enough options to be evaluated after %s.",
4387 fatal_internal("Unknown option %s.", ptr
);
4392 /* This part allows to indicate that an option must be evaluated */
4393 /* before a list of other options. */
4394 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
4400 /* The second argument must be a string. */
4401 /* """"""""""""""""""""""""""""""""""""" */
4402 ptr
= va_arg(args
, char *);
4404 if ((opt
= locate_opt(ptr
)) != NULL
)
4410 ptr
= va_arg(args
, char *);
4414 rtrim(str
, " \t", 0);
4416 /* Feed the list of options to be evaluated before the given option. */
4417 /* This list will contain pointers to options. */
4418 /* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
4419 opt_name
= xstrtok_r(str
, " \t,", &end_str
);
4420 if (opt_name
!= NULL
)
4422 if ((opt_before
= locate_opt(opt_name
)) != NULL
)
4424 ll_append(opt_before
->eval_before_list
, opt
);
4425 while ((opt_name
= xstrtok_r(NULL
, " \t,", &end_str
)) != NULL
)
4427 if ((opt_before
= locate_opt(opt_name
)) != NULL
)
4428 ll_append(opt_before
->eval_before_list
, opt
);
4430 fatal_internal("Unknown option %s.", opt_name
);
4434 fatal_internal("Unknown option %s.", opt_name
);
4437 fatal_internal("Not enough options to be evaluated before %s.",
4443 fatal_internal("Unknown option %s.", ptr
);
4454 /* =============================================================== */
4455 /* This function provides a way to set the behaviour of a context. */
4456 /* =============================================================== */
4458 ctxopt_add_ctx_settings(settings s
, ...)
4467 /* Add a set of mutually incompatible options in a context. */
4468 /* """""""""""""""""""""""""""""""""""""""""""""""""""""""" */
4469 case incompatibilities
:
4476 ptr
= va_arg(args
, char *);
4477 if ((ctx
= locate_ctx(ptr
)) != NULL
)
4479 ptr
= va_arg(args
, char *);
4480 list
= ctx
->incomp_list
;
4484 rtrim(str
, " \t", 0);
4486 n
= strcspn(str
, " \t");
4487 if (n
> 0 && n
< strlen(str
))
4488 ll_append(list
, str
);
4491 "Not enough incompatible options in the string: \"%s\".", str
);
4494 fatal_internal("Unknown context %s.", ptr
);
4498 /* Add functions which will be called when */
4499 /* entering and exiting a context. */
4500 /* """"""""""""""""""""""""""""""""""""""" */
4508 ptr
= va_arg(args
, char *);
4509 if ((ctx
= locate_ctx(ptr
)) != NULL
)
4511 typedef int fn(char *, direction
, char *, int, void **);
4513 function
= va_arg(args
, fn
*);
4514 ctx
->action
= function
;
4516 while ((data
= va_arg(args
, void *)) != NULL
)
4519 ctx
->data
= xrealloc(ctx
->data
, nb_data
* sizeof(void *));
4520 ctx
->data
[nb_data
- 1] = data
;
4522 ctx
->nb_data
= nb_data
;
4525 fatal_internal("Unknown context %s.", ptr
);