Initial release, version 0.0.0.
[gsasl.git] / argp / argp-parse.c
bloba39e7adea75f67fd1c5ea42365aab5d070c47620
1 /* Hierarchial argument parsing
2 Copyright (C) 1995, 96, 97, 98, 99, 2000 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Written by Miles Bader <miles@gnu.ai.mit.edu>.
6 The GNU C Library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Library General Public License as
8 published by the Free Software Foundation; either version 2 of the
9 License, or (at your option) any later version.
11 The GNU C Library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Library General Public License for more details.
16 You should have received a copy of the GNU Library General Public
17 License along with the GNU C Library; see the file COPYING.LIB. If not,
18 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA. */
21 #ifndef _GNU_SOURCE
22 # define _GNU_SOURCE 1
23 #endif
25 #ifdef HAVE_CONFIG_H
26 #include <config.h>
27 #endif
29 #include <stdlib.h>
30 #include <string.h>
31 #include <unistd.h>
32 #include <limits.h>
33 #include <assert.h>
35 #ifndef UNUSED
36 # if __GNUC__ >= 2
37 # define UNUSED __attribute__ ((__unused__))
38 # else
39 # define UNUSED
40 # endif
41 #endif
43 #ifndef _
44 /* This is for other GNU distributions with internationalized messages.
45 When compiling libc, the _ macro is predefined. */
46 # if defined HAVE_LIBINTL_H || defined _LIBC
47 # include <libintl.h>
48 # ifdef _LIBC
49 # undef dgettext
50 # define dgettext(domain, msgid) __dcgettext (domain, msgid, LC_MESSAGES)
51 # endif
52 # else
53 # define dgettext(domain, msgid) (msgid)
54 # define gettext(msgid) (msgid)
55 # endif
56 #endif
57 #ifndef N_
58 # define N_(msgid) (msgid)
59 #endif
61 #if _LIBC - 0
62 #include <bits/libc-lock.h>
63 #else
64 #ifdef HAVE_CTHREADS_H
65 #include <cthreads.h>
66 #endif
67 #endif /* _LIBC */
69 #include "argp.h"
70 #include "argp-namefrob.h"
73 /* The meta-argument used to prevent any further arguments being interpreted
74 as options. */
75 #define QUOTE "--"
77 /* EZ alias for ARGP_ERR_UNKNOWN. */
78 #define EBADKEY ARGP_ERR_UNKNOWN
81 /* Default options. */
83 /* When argp is given the --HANG switch, _ARGP_HANG is set and argp will sleep
84 for one second intervals, decrementing _ARGP_HANG until it's zero. Thus
85 you can force the program to continue by attaching a debugger and setting
86 it to 0 yourself. */
87 volatile int _argp_hang;
89 #define OPT_PROGNAME -2
90 #define OPT_USAGE -3
91 #define OPT_HANG -4
93 static const struct argp_option argp_default_options[] =
95 {"help", '?', 0, 0, N_("Give this help list"), -1},
96 {"usage", OPT_USAGE, 0, 0, N_("Give a short usage message")},
97 {"program-name",OPT_PROGNAME,"NAME", OPTION_HIDDEN, N_("Set the program name")},
98 {"HANG", OPT_HANG, "SECS", OPTION_ARG_OPTIONAL | OPTION_HIDDEN,
99 N_("Hang for SECS seconds (default 3600)")},
100 {0, 0}
103 static error_t
104 argp_default_parser (int key, char *arg, struct argp_state *state)
106 switch (key)
108 case '?':
109 __argp_state_help (state, state->out_stream, ARGP_HELP_STD_HELP);
110 break;
111 case OPT_USAGE:
112 __argp_state_help (state, state->out_stream,
113 ARGP_HELP_USAGE | ARGP_HELP_EXIT_OK);
114 break;
116 case OPT_PROGNAME: /* Set the program name. */
117 #if HAVE_PROGRAM_INVOCATION_NAME
118 program_invocation_name = arg;
119 #endif
120 /* [Note that some systems only have PROGRAM_INVOCATION_SHORT_NAME (aka
121 __PROGNAME), in which case, PROGRAM_INVOCATION_NAME is just defined
122 to be that, so we have to be a bit careful here.] */
124 /* Update what we use for messages. */
126 state->name = __argp_basename(arg);
128 #if HAVE_PROGRAM_INVOCATION_SHORT_NAME
129 program_invocation_short_name = state->name;
130 #endif
132 if ((state->flags & (ARGP_PARSE_ARGV0 | ARGP_NO_ERRS))
133 == ARGP_PARSE_ARGV0)
134 /* Update what getopt uses too. */
135 state->argv[0] = arg;
137 break;
139 case OPT_HANG:
140 _argp_hang = atoi (arg ? arg : "3600");
141 fprintf(state->err_stream, "%s: pid = %ld\n",
142 state->name, (long) getpid());
143 while (_argp_hang-- > 0)
144 __sleep (1);
145 break;
147 default:
148 return EBADKEY;
150 return 0;
153 static const struct argp argp_default_argp =
154 {argp_default_options, &argp_default_parser, NULL, NULL, NULL, NULL, "libc"};
157 static const struct argp_option argp_version_options[] =
159 {"version", 'V', 0, 0, N_("Print program version"), -1},
160 {0, 0}
163 static error_t
164 argp_version_parser (int key, char *arg UNUSED, struct argp_state *state)
166 switch (key)
168 case 'V':
169 if (argp_program_version_hook)
170 (*argp_program_version_hook) (state->out_stream, state);
171 else if (argp_program_version)
172 fprintf (state->out_stream, "%s\n", argp_program_version);
173 else
174 __argp_error (state, dgettext (state->root_argp->argp_domain,
175 "(PROGRAM ERROR) No version known!?"));
176 if (! (state->flags & ARGP_NO_EXIT))
177 exit (0);
178 break;
179 default:
180 return EBADKEY;
182 return 0;
185 static const struct argp argp_version_argp =
186 {argp_version_options, &argp_version_parser, NULL, NULL, NULL, NULL, "libc"};
190 /* The state of a `group' during parsing. Each group corresponds to a
191 particular argp structure from the tree of such descending from the top
192 level argp passed to argp_parse. */
193 struct group
195 /* This group's parsing function. */
196 argp_parser_t parser;
198 /* Which argp this group is from. */
199 const struct argp *argp;
201 /* The number of non-option args sucessfully handled by this parser. */
202 unsigned args_processed;
204 /* This group's parser's parent's group. */
205 struct group *parent;
206 unsigned parent_index; /* And the our position in the parent. */
208 /* These fields are swapped into and out of the state structure when
209 calling this group's parser. */
210 void *input, **child_inputs;
211 void *hook;
214 /* Call GROUP's parser with KEY and ARG, swapping any group-specific info
215 from STATE before calling, and back into state afterwards. If GROUP has
216 no parser, EBADKEY is returned. */
217 static error_t
218 group_parse (struct group *group, struct argp_state *state, int key, char *arg)
220 if (group->parser)
222 error_t err;
223 state->hook = group->hook;
224 state->input = group->input;
225 state->child_inputs = group->child_inputs;
226 state->arg_num = group->args_processed;
227 err = (*group->parser)(key, arg, state);
228 group->hook = state->hook;
229 return err;
231 else
232 return EBADKEY;
235 struct parser
237 const struct argp *argp;
239 const char *posixly_correct;
241 /* True if there are only no-option arguments left, which are just
242 passed verbatim with ARGP_KEY_ARG. This is set if we encounter a
243 quote, or the end of the proper options, but may be cleared again
244 if the user moves the next argument pointer backwards. */
245 int args_only;
247 /* Describe how to deal with options that follow non-option ARGV-elements.
249 If the caller did not specify anything, the default is
250 REQUIRE_ORDER if the environment variable POSIXLY_CORRECT is
251 defined, PERMUTE otherwise.
253 REQUIRE_ORDER means don't recognize them as options; stop option
254 processing when the first non-option is seen. This is what Unix
255 does. This mode of operation is selected by either setting the
256 environment variable POSIXLY_CORRECT, or using `+' as the first
257 character of the list of option characters.
259 PERMUTE is the default. We permute the contents of ARGV as we
260 scan, so that eventually all the non-options are at the end. This
261 allows options to be given in any order, even with programs that
262 were not written to expect this.
264 RETURN_IN_ORDER is an option available to programs that were
265 written to expect options and other ARGV-elements in any order
266 and that care about the ordering of the two. We describe each
267 non-option ARGV-element as if it were the argument of an option
268 with character code 1. Using `-' as the first character of the
269 list of option characters selects this mode of operation.
272 enum { REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER } ordering;
274 /* A segment of non-option arguments that have been skipped for
275 later processing, after all options. `first_nonopt' is the index
276 in ARGV of the first of them; `last_nonopt' is the index after
277 the last of them.
279 If quoted or args_only is non-zero, this segment should be empty. */
281 /* FIXME: I'd prefer to use unsigned, but it's more consistent to
282 use the same type as for state.next. */
283 int first_nonopt;
284 int last_nonopt;
286 /* String of all recognized short options. Needed for ARGP_LONG_ONLY. */
287 /* FIXME: Perhaps change to a pointer to a suitable bitmap instead? */
288 char *short_opts;
290 /* For parsing combined short options. */
291 char *nextchar;
293 /* States of the various parsing groups. */
294 struct group *groups;
295 /* The end of the GROUPS array. */
296 struct group *egroup;
297 /* An vector containing storage for the CHILD_INPUTS field in all groups. */
298 void **child_inputs;
300 /* State block supplied to parsing routines. */
301 struct argp_state state;
303 /* Memory used by this parser. */
304 void *storage;
307 /* Search for a group defining a short option. */
308 static const struct argp_option *
309 find_short_option(struct parser *parser, int key, struct group **p)
311 struct group *group;
313 assert(key >= 0);
314 assert(isascii(key));
316 for (group = parser->groups; group < parser->egroup; group++)
318 const struct argp_option *opts;
320 for (opts = group->argp->options; !__option_is_end(opts); opts++)
321 if (opts->key == key)
323 *p = group;
324 return opts;
327 return NULL;
330 enum match_result { MATCH_EXACT, MATCH_PARTIAL, MATCH_NO };
332 /* If defined, allow complete.el-like abbreviations of long options. */
333 #ifndef ARGP_COMPLETE
334 #define ARGP_COMPLETE 0
335 #endif
337 /* Matches an encountern long-option argument ARG against an option NAME.
338 * ARG is terminated by NUL or '='. */
339 static enum match_result
340 match_option(const char *arg, const char *name)
342 unsigned i, j;
343 for (i = j = 0;; i++, j++)
345 switch(arg[i])
347 case '\0':
348 case '=':
349 return name[j] ? MATCH_PARTIAL : MATCH_EXACT;
350 #if ARGP_COMPLETE
351 case '-':
352 while (name[j] != '-')
353 if (!name[j++])
354 return MATCH_NO;
355 break;
356 #endif
357 default:
358 if (arg[i] != name[j])
359 return MATCH_NO;
364 static const struct argp_option *
365 find_long_option(struct parser *parser,
366 const char *arg,
367 struct group **p)
369 struct group *group;
371 /* Partial match found so far. */
372 struct group *matched_group = NULL;
373 const struct argp_option *matched_option = NULL;
375 /* Number of partial matches. */
376 int num_partial = 0;
378 for (group = parser->groups; group < parser->egroup; group++)
380 const struct argp_option *opts;
382 for (opts = group->argp->options; !__option_is_end(opts); opts++)
384 if (!opts->name)
385 continue;
386 switch (match_option(arg, opts->name))
388 case MATCH_NO:
389 break;
390 case MATCH_PARTIAL:
391 num_partial++;
393 matched_group = group;
394 matched_option = opts;
396 break;
397 case MATCH_EXACT:
398 /* Exact match. */
399 *p = group;
400 return opts;
404 if (num_partial == 1)
406 *p = matched_group;
407 return matched_option;
410 return NULL;
414 /* The next usable entries in the various parser tables being filled in by
415 convert_options. */
416 struct parser_convert_state
418 struct parser *parser;
419 char *short_end;
420 void **child_inputs_end;
423 /* Initialize GROUP from ARGP. If CVT->SHORT_END is non-NULL, short
424 options are recorded in the short options string. Returns the next
425 unused group entry. CVT holds state used during the conversion. */
426 static struct group *
427 convert_options (const struct argp *argp,
428 struct group *parent, unsigned parent_index,
429 struct group *group, struct parser_convert_state *cvt)
431 const struct argp_option *opt = argp->options;
432 const struct argp_child *children = argp->children;
434 if (opt || argp->parser)
436 /* This parser needs a group. */
437 if (cvt->short_end)
439 /* Record any short options. */
440 for ( ; !__option_is_end (opt); opt++)
441 if (__option_is_short(opt))
442 *cvt->short_end++ = opt->key;
445 group->parser = argp->parser;
446 group->argp = argp;
447 group->args_processed = 0;
448 group->parent = parent;
449 group->parent_index = parent_index;
450 group->input = 0;
451 group->hook = 0;
452 group->child_inputs = 0;
454 if (children)
455 /* Assign GROUP's CHILD_INPUTS field some space from
456 CVT->child_inputs_end.*/
458 unsigned num_children = 0;
459 while (children[num_children].argp)
460 num_children++;
461 group->child_inputs = cvt->child_inputs_end;
462 cvt->child_inputs_end += num_children;
464 parent = group++;
466 else
467 parent = 0;
469 if (children)
471 unsigned index = 0;
472 while (children->argp)
473 group =
474 convert_options (children++->argp, parent, index++, group, cvt);
477 return group;
479 /* Allocate and initialize the group structures, so that they are
480 ordered as if by traversing the corresponding argp parser tree in
481 pre-order. Also build the list of short options, if that is needed. */
482 static void
483 parser_convert (struct parser *parser, const struct argp *argp)
485 struct parser_convert_state cvt;
487 cvt.parser = parser;
488 cvt.short_end = parser->short_opts;
489 cvt.child_inputs_end = parser->child_inputs;
491 parser->argp = argp;
493 if (argp)
494 parser->egroup = convert_options (argp, 0, 0, parser->groups, &cvt);
495 else
496 parser->egroup = parser->groups; /* No parsers at all! */
498 if (parser->short_opts)
499 *cvt.short_end ='\0';
502 /* Lengths of various parser fields which we will allocated. */
503 struct parser_sizes
505 /* Needed only ARGP_LONG_ONLY */
506 size_t short_len; /* Number of short options. */
508 size_t num_groups; /* Group structures we allocate. */
509 size_t num_child_inputs; /* Child input slots. */
512 /* For ARGP, increments the NUM_GROUPS field in SZS by the total
513 number of argp structures descended from it, and the SHORT_LEN by
514 the total number of short options. */
515 static void
516 calc_sizes (const struct argp *argp, struct parser_sizes *szs)
518 const struct argp_child *child = argp->children;
519 const struct argp_option *opt = argp->options;
521 if (opt || argp->parser)
523 /* This parser needs a group. */
524 szs->num_groups++;
525 if (opt)
527 while (__option_is_short (opt++))
528 szs->short_len++;
532 if (child)
533 while (child->argp)
535 calc_sizes ((child++)->argp, szs);
536 szs->num_child_inputs++;
540 /* Initializes PARSER to parse ARGP in a manner described by FLAGS. */
541 static error_t
542 parser_init (struct parser *parser, const struct argp *argp,
543 int argc, char **argv, int flags, void *input)
545 error_t err = 0;
546 struct group *group;
547 struct parser_sizes szs;
549 parser->posixly_correct = getenv ("POSIXLY_CORRECT");
551 if (flags & ARGP_IN_ORDER)
552 parser->ordering = RETURN_IN_ORDER;
553 else if (flags & ARGP_NO_ARGS)
554 parser->ordering = REQUIRE_ORDER;
555 else if (parser->posixly_correct)
556 parser->ordering = REQUIRE_ORDER;
557 else
558 parser->ordering = PERMUTE;
560 szs.short_len = 0;
561 szs.num_groups = 0;
562 szs.num_child_inputs = 0;
564 if (argp)
565 calc_sizes (argp, &szs);
567 if (!(flags & ARGP_LONG_ONLY))
568 /* We have no use for the short option array. */
569 szs.short_len = 0;
571 /* Lengths of the various bits of storage used by PARSER. */
572 #define GLEN (szs.num_groups + 1) * sizeof (struct group)
573 #define CLEN (szs.num_child_inputs * sizeof (void *))
574 #define SLEN (szs.short_len + 1)
575 #define STORAGE(offset) ((void *) (((char *) parser->storage) + (offset)))
577 parser->storage = malloc (GLEN + CLEN + SLEN);
578 if (! parser->storage)
579 return ENOMEM;
581 parser->groups = parser->storage;
583 parser->child_inputs = STORAGE(GLEN);
584 memset (parser->child_inputs, 0, szs.num_child_inputs * sizeof (void *));
586 if (flags & ARGP_LONG_ONLY)
587 parser->short_opts = STORAGE(GLEN + CLEN);
588 else
589 parser->short_opts = NULL;
591 parser_convert (parser, argp);
593 memset (&parser->state, 0, sizeof (struct argp_state));
595 parser->state.root_argp = parser->argp;
596 parser->state.argc = argc;
597 parser->state.argv = argv;
598 parser->state.flags = flags;
599 parser->state.err_stream = stderr;
600 parser->state.out_stream = stdout;
601 parser->state.pstate = parser;
603 parser->args_only = 0;
604 parser->nextchar = NULL;
605 parser->first_nonopt = parser->last_nonopt = 0;
607 /* Call each parser for the first time, giving it a chance to propagate
608 values to child parsers. */
609 if (parser->groups < parser->egroup)
610 parser->groups->input = input;
611 for (group = parser->groups;
612 group < parser->egroup && (!err || err == EBADKEY);
613 group++)
615 if (group->parent)
616 /* If a child parser, get the initial input value from the parent. */
617 group->input = group->parent->child_inputs[group->parent_index];
619 if (!group->parser
620 && group->argp->children && group->argp->children->argp)
621 /* For the special case where no parsing function is supplied for an
622 argp, propagate its input to its first child, if any (this just
623 makes very simple wrapper argps more convenient). */
624 group->child_inputs[0] = group->input;
626 err = group_parse (group, &parser->state, ARGP_KEY_INIT, 0);
628 if (err == EBADKEY)
629 err = 0; /* Some parser didn't understand. */
631 if (err)
632 return err;
634 if (argv[0] && !(parser->state.flags & ARGP_PARSE_ARGV0))
635 /* There's an argv[0]; use it for messages. */
637 parser->state.name = __argp_basename(argv[0]);
639 /* Don't parse it as an argument. */
640 parser->state.next = 1;
642 else
643 parser->state.name = __argp_short_program_name(NULL);
645 return 0;
648 /* Free any storage consumed by PARSER (but not PARSER itself). */
649 static error_t
650 parser_finalize (struct parser *parser,
651 error_t err, int arg_ebadkey, int *end_index)
653 struct group *group;
655 if (err == EBADKEY && arg_ebadkey)
656 /* Suppress errors generated by unparsed arguments. */
657 err = 0;
659 if (! err)
661 if (parser->state.next == parser->state.argc)
662 /* We successfully parsed all arguments! Call all the parsers again,
663 just a few more times... */
665 for (group = parser->groups;
666 group < parser->egroup && (!err || err==EBADKEY);
667 group++)
668 if (group->args_processed == 0)
669 err = group_parse (group, &parser->state, ARGP_KEY_NO_ARGS, 0);
670 for (group = parser->egroup - 1;
671 group >= parser->groups && (!err || err==EBADKEY);
672 group--)
673 err = group_parse (group, &parser->state, ARGP_KEY_END, 0);
675 if (err == EBADKEY)
676 err = 0; /* Some parser didn't understand. */
678 /* Tell the user that all arguments are parsed. */
679 if (end_index)
680 *end_index = parser->state.next;
682 else if (end_index)
683 /* Return any remaining arguments to the user. */
684 *end_index = parser->state.next;
685 else
686 /* No way to return the remaining arguments, they must be bogus. */
688 if (!(parser->state.flags & ARGP_NO_ERRS)
689 && parser->state.err_stream)
690 fprintf (parser->state.err_stream,
691 dgettext (parser->argp->argp_domain,
692 "%s: Too many arguments\n"),
693 parser->state.name);
694 err = EBADKEY;
698 /* Okay, we're all done, with either an error or success; call the parsers
699 to indicate which one. */
701 if (err)
703 /* Maybe print an error message. */
704 if (err == EBADKEY)
705 /* An appropriate message describing what the error was should have
706 been printed earlier. */
707 __argp_state_help (&parser->state, parser->state.err_stream,
708 ARGP_HELP_STD_ERR);
710 /* Since we didn't exit, give each parser an error indication. */
711 for (group = parser->groups; group < parser->egroup; group++)
712 group_parse (group, &parser->state, ARGP_KEY_ERROR, 0);
714 else
715 /* Notify parsers of success, and propagate back values from parsers. */
717 /* We pass over the groups in reverse order so that child groups are
718 given a chance to do there processing before passing back a value to
719 the parent. */
720 for (group = parser->egroup - 1
721 ; group >= parser->groups && (!err || err == EBADKEY)
722 ; group--)
723 err = group_parse (group, &parser->state, ARGP_KEY_SUCCESS, 0);
724 if (err == EBADKEY)
725 err = 0; /* Some parser didn't understand. */
728 /* Call parsers once more, to do any final cleanup. Errors are ignored. */
729 for (group = parser->egroup - 1; group >= parser->groups; group--)
730 group_parse (group, &parser->state, ARGP_KEY_FINI, 0);
732 if (err == EBADKEY)
733 err = EINVAL;
735 free (parser->storage);
737 return err;
740 /* Call the user parsers to parse the non-option argument VAL, at the
741 current position, returning any error. The state NEXT pointer
742 should point to the argument; this function will adjust it
743 correctly to reflect however many args actually end up being
744 consumed. */
745 static error_t
746 parser_parse_arg (struct parser *parser, char *val)
748 /* Save the starting value of NEXT */
749 int index = parser->state.next;
750 error_t err = EBADKEY;
751 struct group *group;
752 int key = 0; /* Which of ARGP_KEY_ARG[S] we used. */
754 /* Try to parse the argument in each parser. */
755 for (group = parser->groups
756 ; group < parser->egroup && err == EBADKEY
757 ; group++)
759 parser->state.next++; /* For ARGP_KEY_ARG, consume the arg. */
760 key = ARGP_KEY_ARG;
761 err = group_parse (group, &parser->state, key, val);
763 if (err == EBADKEY)
764 /* This parser doesn't like ARGP_KEY_ARG; try ARGP_KEY_ARGS instead. */
766 parser->state.next--; /* For ARGP_KEY_ARGS, put back the arg. */
767 key = ARGP_KEY_ARGS;
768 err = group_parse (group, &parser->state, key, 0);
772 if (! err)
774 if (key == ARGP_KEY_ARGS)
775 /* The default for ARGP_KEY_ARGS is to assume that if NEXT isn't
776 changed by the user, *all* arguments should be considered
777 consumed. */
778 parser->state.next = parser->state.argc;
780 if (parser->state.next > index)
781 /* Remember that we successfully processed a non-option
782 argument -- but only if the user hasn't gotten tricky and set
783 the clock back. */
784 (--group)->args_processed += (parser->state.next - index);
785 else
786 /* The user wants to reparse some args, so try looking for options again. */
787 parser->args_only = 0;
790 return err;
793 /* Exchange two adjacent subsequences of ARGV.
794 One subsequence is elements [first_nonopt,last_nonopt)
795 which contains all the non-options that have been skipped so far.
796 The other is elements [last_nonopt,next), which contains all
797 the options processed since those non-options were skipped.
799 `first_nonopt' and `last_nonopt' are relocated so that they describe
800 the new indices of the non-options in ARGV after they are moved. */
802 static void
803 exchange (struct parser *parser)
805 int bottom = parser->first_nonopt;
806 int middle = parser->last_nonopt;
807 int top = parser->state.next;
808 char **argv = parser->state.argv;
810 char *tem;
812 /* Exchange the shorter segment with the far end of the longer segment.
813 That puts the shorter segment into the right place.
814 It leaves the longer segment in the right place overall,
815 but it consists of two parts that need to be swapped next. */
817 while (top > middle && middle > bottom)
819 if (top - middle > middle - bottom)
821 /* Bottom segment is the short one. */
822 int len = middle - bottom;
823 register int i;
825 /* Swap it with the top part of the top segment. */
826 for (i = 0; i < len; i++)
828 tem = argv[bottom + i];
829 argv[bottom + i] = argv[top - (middle - bottom) + i];
830 argv[top - (middle - bottom) + i] = tem;
832 /* Exclude the moved bottom segment from further swapping. */
833 top -= len;
835 else
837 /* Top segment is the short one. */
838 int len = top - middle;
839 register int i;
841 /* Swap it with the bottom part of the bottom segment. */
842 for (i = 0; i < len; i++)
844 tem = argv[bottom + i];
845 argv[bottom + i] = argv[middle + i];
846 argv[middle + i] = tem;
848 /* Exclude the moved top segment from further swapping. */
849 bottom += len;
853 /* Update records for the slots the non-options now occupy. */
855 parser->first_nonopt += (parser->state.next - parser->last_nonopt);
856 parser->last_nonopt = parser->state.next;
861 enum arg_type { ARG_ARG, ARG_SHORT_OPTION,
862 ARG_LONG_OPTION, ARG_LONG_ONLY_OPTION,
863 ARG_QUOTE };
865 static enum arg_type
866 classify_arg(struct parser *parser, char *arg, char **opt)
868 if (arg[0] == '-')
869 /* Looks like an option... */
870 switch (arg[1])
872 case '\0':
873 /* "-" is not an option. */
874 return ARG_ARG;
875 case '-':
876 /* Long option, or quote. */
877 if (!arg[2])
878 return ARG_QUOTE;
880 /* A long option. */
881 if (opt)
882 *opt = arg + 2;
883 return ARG_LONG_OPTION;
885 default:
886 /* Short option. But if ARGP_LONG_ONLY, it can also be a long option. */
888 if (opt)
889 *opt = arg + 1;
891 if (parser->state.flags & ARGP_LONG_ONLY)
893 /* Rules from getopt.c:
895 If long_only and the ARGV-element has the form "-f",
896 where f is a valid short option, don't consider it an
897 abbreviated form of a long option that starts with f.
898 Otherwise there would be no way to give the -f short
899 option.
901 On the other hand, if there's a long option "fubar" and
902 the ARGV-element is "-fu", do consider that an
903 abbreviation of the long option, just like "--fu", and
904 not "-f" with arg "u".
906 This distinction seems to be the most useful approach. */
908 assert(parser->short_opts);
910 if (arg[2] || !strchr(parser->short_opts, arg[1]))
911 return ARG_LONG_ONLY_OPTION;
914 return ARG_SHORT_OPTION;
917 else
918 return ARG_ARG;
921 /* Parse the next argument in PARSER (as indicated by PARSER->state.next).
922 Any error from the parsers is returned, and *ARGP_EBADKEY indicates
923 whether a value of EBADKEY is due to an unrecognized argument (which is
924 generally not fatal). */
925 static error_t
926 parser_parse_next (struct parser *parser, int *arg_ebadkey)
928 if (parser->state.quoted && parser->state.next < parser->state.quoted)
929 /* The next argument pointer has been moved to before the quoted
930 region, so pretend we never saw the quoting `--', and start
931 looking for options again. If the `--' is still there we'll just
932 process it one more time. */
933 parser->state.quoted = parser->args_only = 0;
935 /* Give FIRST_NONOPT & LAST_NONOPT rational values if NEXT has been
936 moved back by the user (who may also have changed the arguments). */
937 if (parser->last_nonopt > parser->state.next)
938 parser->last_nonopt = parser->state.next;
939 if (parser->first_nonopt > parser->state.next)
940 parser->first_nonopt = parser->state.next;
942 if (parser->nextchar)
943 /* Deal with short options. */
945 struct group *group;
946 char c;
947 const struct argp_option *option;
948 char *value = NULL;;
950 assert(!parser->args_only);
952 c = *parser->nextchar++;
954 option = find_short_option(parser, c, &group);
955 if (!option)
957 if (parser->posixly_correct)
958 /* 1003.2 specifies the format of this message. */
959 fprintf (parser->state.err_stream,
960 dgettext(parser->state.root_argp->argp_domain,
961 "%s: illegal option -- %c\n"),
962 parser->state.name, c);
963 else
964 fprintf (parser->state.err_stream,
965 dgettext(parser->state.root_argp->argp_domain,
966 "%s: invalid option -- %c\n"),
967 parser->state.name, c);
969 *arg_ebadkey = 0;
970 return EBADKEY;
973 if (!*parser->nextchar)
974 parser->nextchar = NULL;
976 if (option->arg)
978 value = parser->nextchar;
979 parser->nextchar = NULL;
981 if (!value
982 && !(option->flags & OPTION_ARG_OPTIONAL))
983 /* We need an mandatory argument. */
985 if (parser->state.next == parser->state.argc)
986 /* Missing argument */
988 /* 1003.2 specifies the format of this message. */
989 fprintf (parser->state.err_stream,
990 dgettext(parser->state.root_argp->argp_domain,
991 "%s: option requires an argument -- %c\n"),
992 parser->state.name, c);
994 *arg_ebadkey = 0;
995 return EBADKEY;
997 value = parser->state.argv[parser->state.next++];
1000 return group_parse(group, &parser->state,
1001 option->key, value);
1003 else
1004 /* Advance to the next ARGV-element. */
1006 if (parser->args_only)
1008 *arg_ebadkey = 1;
1009 if (parser->state.next >= parser->state.argc)
1010 /* We're done. */
1011 return EBADKEY;
1012 else
1013 return parser_parse_arg(parser,
1014 parser->state.argv[parser->state.next]);
1017 if (parser->state.next >= parser->state.argc)
1018 /* Almost done. If there are non-options that we skipped
1019 previously, we should process them now. */
1021 *arg_ebadkey = 1;
1022 if (parser->first_nonopt != parser->last_nonopt)
1024 /* Start processing the arguments we skipped previously. */
1025 parser->state.next = parser->first_nonopt;
1027 parser->first_nonopt = parser->last_nonopt = 0;
1029 parser->args_only = 1;
1030 return 0;
1032 else
1033 /* Indicate that we're really done. */
1034 return EBADKEY;
1036 else
1037 /* Look for options. */
1039 char *arg = parser->state.argv[parser->state.next];
1041 char *optstart;
1042 enum arg_type token = classify_arg(parser, arg, &optstart);
1044 switch (token)
1046 case ARG_ARG:
1047 switch (parser->ordering)
1049 case PERMUTE:
1050 if (parser->first_nonopt == parser->last_nonopt)
1051 /* Skipped sequence is empty; start a new one. */
1052 parser->first_nonopt = parser->last_nonopt = parser->state.next;
1054 else if (parser->last_nonopt != parser->state.next)
1055 /* We have a non-empty skipped sequence, and
1056 we're not at the end-point, so move it. */
1057 exchange(parser);
1059 assert(parser->last_nonopt == parser->state.next);
1061 /* Skip this argument for now. */
1062 parser->state.next++;
1063 parser->last_nonopt = parser->state.next;
1065 return 0;
1067 case REQUIRE_ORDER:
1068 /* Implicit quote before the first argument. */
1069 parser->args_only = 1;
1070 return 0;
1072 case RETURN_IN_ORDER:
1073 *arg_ebadkey = 1;
1074 return parser_parse_arg(parser, arg);
1076 default:
1077 abort();
1079 case ARG_QUOTE:
1080 /* Skip it, then exchange with any previous non-options. */
1081 parser->state.next++;
1082 assert (parser->last_nonopt != parser->state.next);
1084 if (parser->first_nonopt != parser->last_nonopt)
1086 exchange(parser);
1088 /* Start processing the skipped and the quoted
1089 arguments. */
1091 parser->state.quoted = parser->state.next = parser->first_nonopt;
1093 /* Also empty the skipped-list, to avoid confusion
1094 if the user resets the next pointer. */
1095 parser->first_nonopt = parser->last_nonopt = 0;
1097 else
1098 parser->state.quoted = parser->state.next;
1100 parser->args_only = 1;
1101 return 0;
1103 case ARG_LONG_ONLY_OPTION:
1104 case ARG_LONG_OPTION:
1106 struct group *group;
1107 const struct argp_option *option;
1108 char *value;
1110 parser->state.next++;
1111 option = find_long_option(parser, optstart, &group);
1113 if (!option)
1115 /* NOTE: This includes any "=something" in the output. */
1116 fprintf (parser->state.err_stream,
1117 dgettext(parser->state.root_argp->argp_domain,
1118 "%s: unrecognized option `%s'\n"),
1119 parser->state.name, arg);
1120 *arg_ebadkey = 0;
1121 return EBADKEY;
1124 value = strchr(optstart, '=');
1125 if (value)
1126 value++;
1128 if (value && !option->arg)
1129 /* Unexpected argument. */
1131 if (token == ARG_LONG_OPTION)
1132 /* --option */
1133 fprintf (parser->state.err_stream,
1134 dgettext(parser->state.root_argp->argp_domain,
1135 "%s: option `--%s' doesn't allow an argument\n"),
1136 parser->state.name, option->name);
1137 else
1138 /* +option or -option */
1139 fprintf (parser->state.err_stream,
1140 dgettext(parser->state.root_argp->argp_domain,
1141 "%s: option `%c%s' doesn't allow an argument\n"),
1142 parser->state.name, arg[0], option->name);
1144 *arg_ebadkey = 0;
1145 return EBADKEY;
1148 if (option->arg && !value
1149 && !(option->flags & OPTION_ARG_OPTIONAL))
1150 /* We need an mandatory argument. */
1152 if (parser->state.next == parser->state.argc)
1153 /* Missing argument */
1155 if (token == ARG_LONG_OPTION)
1156 /* --option */
1157 fprintf (parser->state.err_stream,
1158 dgettext(parser->state.root_argp->argp_domain,
1159 "%s: option `--%s' requires an argument\n"),
1160 parser->state.name, option->name);
1161 else
1162 /* +option or -option */
1163 fprintf (parser->state.err_stream,
1164 dgettext(parser->state.root_argp->argp_domain,
1165 "%s: option `%c%s' requires an argument\n"),
1166 parser->state.name, arg[0], option->name);
1168 *arg_ebadkey = 0;
1169 return EBADKEY;
1172 value = parser->state.argv[parser->state.next++];
1174 *arg_ebadkey = 0;
1175 return group_parse(group, &parser->state,
1176 option->key, value);
1178 case ARG_SHORT_OPTION:
1179 parser->state.next++;
1180 parser->nextchar = optstart;
1181 return 0;
1183 default:
1184 abort();
1190 /* Parse the options strings in ARGC & ARGV according to the argp in ARGP.
1191 FLAGS is one of the ARGP_ flags above. If END_INDEX is non-NULL, the
1192 index in ARGV of the first unparsed option is returned in it. If an
1193 unknown option is present, EINVAL is returned; if some parser routine
1194 returned a non-zero value, it is returned; otherwise 0 is returned. */
1195 error_t
1196 __argp_parse (const struct argp *argp, int argc, char **argv, unsigned flags,
1197 int *end_index, void *input)
1199 error_t err;
1200 struct parser parser;
1202 /* If true, then err == EBADKEY is a result of a non-option argument failing
1203 to be parsed (which in some cases isn't actually an error). */
1204 int arg_ebadkey = 0;
1206 if (! (flags & ARGP_NO_HELP))
1207 /* Add our own options. */
1209 struct argp_child *child = malloc (4 * sizeof (struct argp_child));
1210 struct argp *top_argp = malloc (sizeof (struct argp));
1212 /* TOP_ARGP has no options, it just serves to group the user & default
1213 argps. */
1214 memset (top_argp, 0, sizeof (*top_argp));
1215 top_argp->children = child;
1217 memset (child, 0, 4 * sizeof (struct argp_child));
1219 if (argp)
1220 (child++)->argp = argp;
1221 (child++)->argp = &argp_default_argp;
1222 if (argp_program_version || argp_program_version_hook)
1223 (child++)->argp = &argp_version_argp;
1224 child->argp = 0;
1226 argp = top_argp;
1229 /* Construct a parser for these arguments. */
1230 err = parser_init (&parser, argp, argc, argv, flags, input);
1232 if (! err)
1233 /* Parse! */
1235 while (! err)
1236 err = parser_parse_next (&parser, &arg_ebadkey);
1237 err = parser_finalize (&parser, err, arg_ebadkey, end_index);
1240 return err;
1242 #ifdef weak_alias
1243 weak_alias (__argp_parse, argp_parse)
1244 #endif
1246 /* Return the input field for ARGP in the parser corresponding to STATE; used
1247 by the help routines. */
1248 void *
1249 __argp_input (const struct argp *argp, const struct argp_state *state)
1251 if (state)
1253 struct group *group;
1254 struct parser *parser = state->pstate;
1256 for (group = parser->groups; group < parser->egroup; group++)
1257 if (group->argp == argp)
1258 return group->input;
1261 return 0;
1263 #ifdef weak_alias
1264 weak_alias (__argp_input, _argp_input)
1265 #endif
1267 /* Defined here, in case a user is not inlining the definitions in
1268 * argp.h */
1269 void
1270 __argp_usage (__const struct argp_state *__state) __THROW
1272 __argp_state_help (__state, stderr, ARGP_HELP_STD_USAGE);
1276 __option_is_short (__const struct argp_option *__opt) __THROW
1278 if (__opt->flags & OPTION_DOC)
1279 return 0;
1280 else
1282 int __key = __opt->key;
1283 /* FIXME: whether or not a particular key implies a short option
1284 * ought not to be locale dependent. */
1285 return __key > 0 && isprint (__key);
1290 __option_is_end (__const struct argp_option *__opt) __THROW
1292 return !__opt->key && !__opt->name && !__opt->doc && !__opt->group;