libm: fix nexttoward failures, fixed by sorear
[uclibc-ng.git] / libuargp / argp-parse.c
blob030bc4f9f22687120e8574722758c1f5e5e99d3e
1 /* Hierarchial argument parsing, layered over getopt
2 Copyright (C) 1995-2000, 2002, 2003, 2004 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Written by Miles Bader <miles at 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 Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the 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 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public
17 License along with the GNU C Library; see the file COPYING.LIB. If
18 not, see <http://www.gnu.org/licenses/>.
20 Modified for uClibc by: Salvatore Cro <salvatore.cro at st.com>
23 #ifdef HAVE_CONFIG_H
24 #include <config.h>
25 #endif
27 /* AIX requires this to be the first thing in the file. */
28 #ifndef __GNUC__
29 # if HAVE_ALLOCA_H || defined _LIBC
30 # include <alloca.h>
31 # else
32 # ifdef _AIX
33 #pragma alloca
34 # else
35 # ifndef alloca /* predefined by HP cc +Olibcalls */
36 char *alloca ();
37 # endif
38 # endif
39 # endif
40 #endif
42 #include <stdlib.h>
43 #include <string.h>
44 #include <unistd.h>
45 #include <limits.h>
46 #include <getopt.h>
47 #include <bits/getopt_int.h>
49 #include <features.h>
50 #ifndef _
51 # define dgettext(domain, msgid) (msgid)
52 # define gettext(msgid) (msgid)
53 #endif
54 #ifndef N_
55 # define N_(msgid) (msgid)
56 #endif
58 #include <argp.h>
60 /* Getopt return values. */
61 #define KEY_END (-1) /* The end of the options. */
62 #define KEY_ARG 1 /* A non-option argument. */
63 #define KEY_ERR '?' /* An error parsing the options. */
65 /* The meta-argument used to prevent any further arguments being interpreted
66 as options. */
67 #define QUOTE "--"
69 /* The number of bits we steal in a long-option value for our own use. */
70 #define GROUP_BITS CHAR_BIT
72 /* The number of bits available for the user value. */
73 #define USER_BITS ((sizeof ((struct option *)0)->val * CHAR_BIT) - GROUP_BITS)
74 #define USER_MASK ((1 << USER_BITS) - 1)
76 /* EZ alias for ARGP_ERR_UNKNOWN. */
77 #define EBADKEY ARGP_ERR_UNKNOWN
79 /* Default options. */
81 /* When argp is given the --HANG switch, _ARGP_HANG is set and argp will sleep
82 for one second intervals, decrementing _ARGP_HANG until it's zero. Thus
83 you can force the program to continue by attaching a debugger and setting
84 it to 0 yourself. */
85 static volatile int _argp_hang;
87 #define OPT_PROGNAME -2
88 #define OPT_USAGE -3
89 #define OPT_HANG -4
91 static const struct argp_option argp_default_options[] =
93 {"help", '?', 0, 0, N_("Give this help list"), -1},
94 {"usage", OPT_USAGE, 0, 0, N_("Give a short usage message")},
95 {"program-name",OPT_PROGNAME,"NAME", OPTION_HIDDEN, N_("Set the program name")},
96 {"HANG", OPT_HANG, "SECS", OPTION_ARG_OPTIONAL | OPTION_HIDDEN,
97 N_("Hang for SECS seconds (default 3600)")},
98 {0, 0}
101 static error_t
102 argp_default_parser (int key, char *arg, struct argp_state *state)
104 switch (key)
106 case '?':
107 argp_state_help (state, state->out_stream, ARGP_HELP_STD_HELP);
108 break;
109 case OPT_USAGE:
110 argp_state_help (state, state->out_stream,
111 ARGP_HELP_USAGE | ARGP_HELP_EXIT_OK);
112 break;
114 case OPT_PROGNAME: /* Set the program name. */
115 #if defined _LIBC && defined(__UCLIBC_HAS_PROGRAM_INVOCATION_NAME__)
116 program_invocation_name = arg;
117 #endif
118 /* [Note that some systems only have PROGRAM_INVOCATION_SHORT_NAME (aka
119 __PROGNAME), in which case, PROGRAM_INVOCATION_NAME is just defined
120 to be that, so we have to be a bit careful here.] */
122 /* Update what we use for messages. */
123 state->name = strrchr (arg, '/');
124 if (state->name)
125 state->name++;
126 else
127 state->name = arg;
129 #if defined _LIBC && defined(__UCLIBC_HAS_PROGRAM_INVOCATION_NAME__)
130 program_invocation_short_name = state->name;
131 #endif
133 if ((state->flags & (ARGP_PARSE_ARGV0 | ARGP_NO_ERRS))
134 == ARGP_PARSE_ARGV0)
135 /* Update what getopt uses too. */
136 state->argv[0] = arg;
138 break;
140 case OPT_HANG:
141 _argp_hang = atoi (arg ? arg : "3600");
142 while (_argp_hang-- > 0)
143 sleep (1);
144 break;
146 default:
147 return EBADKEY;
149 return 0;
152 static const struct argp argp_default_argp =
153 {argp_default_options, &argp_default_parser, NULL, NULL, NULL, NULL, "libc"};
156 static const struct argp_option argp_version_options[] =
158 {"version", 'V', 0, 0, N_("Print program version"), -1},
159 {0, 0}
162 static error_t
163 argp_version_parser (int key, char *arg, struct argp_state *state)
165 switch (key)
167 case 'V':
168 if (argp_program_version_hook)
169 (*argp_program_version_hook) (state->out_stream, state);
170 else if (argp_program_version)
171 fprintf (state->out_stream, "%s\n", argp_program_version);
172 else
173 argp_error (state, dgettext (state->root_argp->argp_domain,
174 "(PROGRAM ERROR) No version known!?"));
175 if (! (state->flags & ARGP_NO_EXIT))
176 exit (0);
177 break;
178 default:
179 return EBADKEY;
181 return 0;
184 static const struct argp argp_version_argp =
185 {argp_version_options, &argp_version_parser, NULL, NULL, NULL, NULL, "libc"};
187 /* Returns the offset into the getopt long options array LONG_OPTIONS of a
188 long option with called NAME, or -1 if none is found. Passing NULL as
189 NAME will return the number of options. */
190 static int
191 find_long_option (struct option *long_options, const char *name)
193 struct option *l = long_options;
194 while (l->name != NULL)
195 if (name != NULL && strcmp (l->name, name) == 0)
196 return l - long_options;
197 else
198 l++;
199 if (name == NULL)
200 return l - long_options;
201 else
202 return -1;
206 /* The state of a `group' during parsing. Each group corresponds to a
207 particular argp structure from the tree of such descending from the top
208 level argp passed to argp_parse. */
209 struct group
211 /* This group's parsing function. */
212 argp_parser_t parser;
214 /* Which argp this group is from. */
215 const struct argp *argp;
217 /* Points to the point in SHORT_OPTS corresponding to the end of the short
218 options for this group. We use it to determine from which group a
219 particular short options is from. */
220 char *short_end;
222 /* The number of non-option args sucessfully handled by this parser. */
223 unsigned args_processed;
225 /* This group's parser's parent's group. */
226 struct group *parent;
227 unsigned parent_index; /* And the our position in the parent. */
229 /* These fields are swapped into and out of the state structure when
230 calling this group's parser. */
231 void *input, **child_inputs;
232 void *hook;
235 /* Call GROUP's parser with KEY and ARG, swapping any group-specific info
236 from STATE before calling, and back into state afterwards. If GROUP has
237 no parser, EBADKEY is returned. */
238 static error_t
239 group_parse (struct group *group, struct argp_state *state, int key, char *arg)
241 if (group->parser)
243 error_t err;
244 state->hook = group->hook;
245 state->input = group->input;
246 state->child_inputs = group->child_inputs;
247 state->arg_num = group->args_processed;
248 err = (*group->parser)(key, arg, state);
249 group->hook = state->hook;
250 return err;
252 else
253 return EBADKEY;
256 struct parser
258 const struct argp *argp;
260 /* SHORT_OPTS is the getopt short options string for the union of all the
261 groups of options. */
262 char *short_opts;
263 /* LONG_OPTS is the array of getop long option structures for the union of
264 all the groups of options. */
265 struct option *long_opts;
266 /* OPT_DATA is the getopt data used for the re-entrant getopt. */
267 struct _getopt_data opt_data;
269 /* States of the various parsing groups. */
270 struct group *groups;
271 /* The end of the GROUPS array. */
272 struct group *egroup;
273 /* An vector containing storage for the CHILD_INPUTS field in all groups. */
274 void **child_inputs;
276 /* True if we think using getopt is still useful; if false, then
277 remaining arguments are just passed verbatim with ARGP_KEY_ARG. This is
278 cleared whenever getopt returns KEY_END, but may be set again if the user
279 moves the next argument pointer backwards. */
280 int try_getopt;
282 /* State block supplied to parsing routines. */
283 struct argp_state state;
285 /* Memory used by this parser. */
286 void *storage;
289 /* The next usable entries in the various parser tables being filled in by
290 convert_options. */
291 struct parser_convert_state
293 struct parser *parser;
294 char *short_end;
295 struct option *long_end;
296 void **child_inputs_end;
299 /* Converts all options in ARGP (which is put in GROUP) and ancestors
300 into getopt options stored in SHORT_OPTS and LONG_OPTS; SHORT_END and
301 CVT->LONG_END are the points at which new options are added. Returns the
302 next unused group entry. CVT holds state used during the conversion. */
303 static struct group *
304 convert_options (const struct argp *argp,
305 struct group *parent, unsigned parent_index,
306 struct group *group, struct parser_convert_state *cvt)
308 /* REAL is the most recent non-alias value of OPT. */
309 const struct argp_option *real = argp->options;
310 const struct argp_child *children = argp->children;
312 if (real || argp->parser)
314 const struct argp_option *opt;
316 if (real)
317 for (opt = real; !__option_is_end (opt); opt++)
319 if (! (opt->flags & OPTION_ALIAS))
320 /* OPT isn't an alias, so we can use values from it. */
321 real = opt;
323 if (! (real->flags & OPTION_DOC))
324 /* A real option (not just documentation). */
326 if (__option_is_short (opt))
327 /* OPT can be used as a short option. */
329 *cvt->short_end++ = opt->key;
330 if (real->arg)
332 *cvt->short_end++ = ':';
333 if (real->flags & OPTION_ARG_OPTIONAL)
334 *cvt->short_end++ = ':';
336 *cvt->short_end = '\0'; /* keep 0 terminated */
339 if (opt->name
340 && find_long_option (cvt->parser->long_opts, opt->name) < 0)
341 /* OPT can be used as a long option. */
343 cvt->long_end->name = opt->name;
344 cvt->long_end->has_arg =
345 (real->arg
346 ? (real->flags & OPTION_ARG_OPTIONAL
347 ? optional_argument
348 : required_argument)
349 : no_argument);
350 cvt->long_end->flag = 0;
351 /* we add a disambiguating code to all the user's
352 values (which is removed before we actually call
353 the function to parse the value); this means that
354 the user loses use of the high 8 bits in all his
355 values (the sign of the lower bits is preserved
356 however)... */
357 cvt->long_end->val =
358 ((opt->key | real->key) & USER_MASK)
359 + (((group - cvt->parser->groups) + 1) << USER_BITS);
361 /* Keep the LONG_OPTS list terminated. */
362 (++cvt->long_end)->name = NULL;
367 group->parser = argp->parser;
368 group->argp = argp;
369 group->short_end = cvt->short_end;
370 group->args_processed = 0;
371 group->parent = parent;
372 group->parent_index = parent_index;
373 group->input = 0;
374 group->hook = 0;
375 group->child_inputs = 0;
377 if (children)
378 /* Assign GROUP's CHILD_INPUTS field some space from
379 CVT->child_inputs_end.*/
381 unsigned num_children = 0;
382 while (children[num_children].argp)
383 num_children++;
384 group->child_inputs = cvt->child_inputs_end;
385 cvt->child_inputs_end += num_children;
388 parent = group++;
390 else
391 parent = 0;
393 if (children)
395 unsigned index = 0;
396 while (children->argp)
397 group =
398 convert_options (children++->argp, parent, index++, group, cvt);
401 return group;
404 /* Find the merged set of getopt options, with keys appropiately prefixed. */
405 static void
406 parser_convert (struct parser *parser, const struct argp *argp, int flags)
408 struct parser_convert_state cvt;
410 cvt.parser = parser;
411 cvt.short_end = parser->short_opts;
412 cvt.long_end = parser->long_opts;
413 cvt.child_inputs_end = parser->child_inputs;
415 if (flags & ARGP_IN_ORDER)
416 *cvt.short_end++ = '-';
417 else if (flags & ARGP_NO_ARGS)
418 *cvt.short_end++ = '+';
419 *cvt.short_end = '\0';
421 cvt.long_end->name = NULL;
423 parser->argp = argp;
425 if (argp)
426 parser->egroup = convert_options (argp, 0, 0, parser->groups, &cvt);
427 else
428 parser->egroup = parser->groups; /* No parsers at all! */
431 /* Lengths of various parser fields which we will allocated. */
432 struct parser_sizes
434 size_t short_len; /* Getopt short options string. */
435 size_t long_len; /* Getopt long options vector. */
436 size_t num_groups; /* Group structures we allocate. */
437 size_t num_child_inputs; /* Child input slots. */
440 /* For ARGP, increments the NUM_GROUPS field in SZS by the total number of
441 argp structures descended from it, and the SHORT_LEN & LONG_LEN fields by
442 the maximum lengths of the resulting merged getopt short options string and
443 long-options array, respectively. */
444 static void
445 calc_sizes (const struct argp *argp, struct parser_sizes *szs)
447 const struct argp_child *child = argp->children;
448 const struct argp_option *opt = argp->options;
450 if (opt || argp->parser)
452 szs->num_groups++;
453 if (opt)
455 int num_opts = 0;
456 while (!__option_is_end (opt++))
457 num_opts++;
458 szs->short_len += num_opts * 3; /* opt + up to 2 `:'s */
459 szs->long_len += num_opts;
463 if (child)
464 while (child->argp)
466 calc_sizes ((child++)->argp, szs);
467 szs->num_child_inputs++;
472 extern char * __argp_short_program_name (void);
473 /* Initializes PARSER to parse ARGP in a manner described by FLAGS. */
474 static error_t
475 parser_init (struct parser *parser, const struct argp *argp,
476 int argc, char **argv, int flags, void *input)
478 error_t err = 0;
479 struct group *group;
480 struct parser_sizes szs;
481 struct _getopt_data opt_data = _GETOPT_DATA_INITIALIZER;
483 szs.short_len = (flags & ARGP_NO_ARGS) ? 0 : 1;
484 szs.long_len = 0;
485 szs.num_groups = 0;
486 szs.num_child_inputs = 0;
488 if (argp)
489 calc_sizes (argp, &szs);
491 /* Lengths of the various bits of storage used by PARSER. */
492 #define GLEN (szs.num_groups + 1) * sizeof (struct group)
493 #define CLEN (szs.num_child_inputs * sizeof (void *))
494 #define LLEN ((szs.long_len + 1) * sizeof (struct option))
495 #define SLEN (szs.short_len + 1)
497 parser->storage = malloc (GLEN + CLEN + LLEN + SLEN);
498 if (! parser->storage)
499 return ENOMEM;
501 parser->groups = parser->storage;
502 parser->child_inputs = parser->storage + GLEN;
503 parser->long_opts = parser->storage + GLEN + CLEN;
504 parser->short_opts = parser->storage + GLEN + CLEN + LLEN;
505 parser->opt_data = opt_data;
507 memset (parser->child_inputs, 0, szs.num_child_inputs * sizeof (void *));
508 parser_convert (parser, argp, flags);
510 memset (&parser->state, 0, sizeof (struct argp_state));
511 parser->state.root_argp = parser->argp;
512 parser->state.argc = argc;
513 parser->state.argv = argv;
514 parser->state.flags = flags;
515 parser->state.err_stream = stderr;
516 parser->state.out_stream = stdout;
517 parser->state.next = 0; /* Tell getopt to initialize. */
518 parser->state.pstate = parser;
520 parser->try_getopt = 1;
522 /* Call each parser for the first time, giving it a chance to propagate
523 values to child parsers. */
524 if (parser->groups < parser->egroup)
525 parser->groups->input = input;
526 for (group = parser->groups;
527 group < parser->egroup && (!err || err == EBADKEY);
528 group++)
530 if (group->parent)
531 /* If a child parser, get the initial input value from the parent. */
532 group->input = group->parent->child_inputs[group->parent_index];
534 if (!group->parser
535 && group->argp->children && group->argp->children->argp)
536 /* For the special case where no parsing function is supplied for an
537 argp, propagate its input to its first child, if any (this just
538 makes very simple wrapper argps more convenient). */
539 group->child_inputs[0] = group->input;
541 err = group_parse (group, &parser->state, ARGP_KEY_INIT, 0);
543 if (err == EBADKEY)
544 err = 0; /* Some parser didn't understand. */
546 if (err)
547 return err;
549 if (parser->state.flags & ARGP_NO_ERRS)
551 parser->opt_data.opterr = 0;
552 if (parser->state.flags & ARGP_PARSE_ARGV0)
553 /* getopt always skips ARGV[0], so we have to fake it out. As long
554 as OPTERR is 0, then it shouldn't actually try to access it. */
555 parser->state.argv--, parser->state.argc++;
557 else
558 parser->opt_data.opterr = 1; /* Print error messages. */
560 if (parser->state.argv == argv && argv[0])
561 /* There's an argv[0]; use it for messages. */
563 char *short_name = strrchr (argv[0], '/');
564 parser->state.name = short_name ? short_name + 1 : argv[0];
566 else
567 parser->state.name = __argp_short_program_name ();
569 return 0;
572 /* Free any storage consumed by PARSER (but not PARSER itself). */
573 static error_t
574 parser_finalize (struct parser *parser,
575 error_t err, int arg_ebadkey, int *end_index)
577 struct group *group;
579 if (err == EBADKEY && arg_ebadkey)
580 /* Suppress errors generated by unparsed arguments. */
581 err = 0;
583 if (! err)
585 if (parser->state.next == parser->state.argc)
586 /* We successfully parsed all arguments! Call all the parsers again,
587 just a few more times... */
589 for (group = parser->groups;
590 group < parser->egroup && (!err || err==EBADKEY);
591 group++)
592 if (group->args_processed == 0)
593 err = group_parse (group, &parser->state, ARGP_KEY_NO_ARGS, 0);
594 for (group = parser->egroup - 1;
595 group >= parser->groups && (!err || err==EBADKEY);
596 group--)
597 err = group_parse (group, &parser->state, ARGP_KEY_END, 0);
599 if (err == EBADKEY)
600 err = 0; /* Some parser didn't understand. */
602 /* Tell the user that all arguments are parsed. */
603 if (end_index)
604 *end_index = parser->state.next;
606 else if (end_index)
607 /* Return any remaining arguments to the user. */
608 *end_index = parser->state.next;
609 else
610 /* No way to return the remaining arguments, they must be bogus. */
612 if (!(parser->state.flags & ARGP_NO_ERRS)
613 && parser->state.err_stream)
614 fprintf (parser->state.err_stream,
615 dgettext (parser->argp->argp_domain,
616 "%s: Too many arguments\n"),
617 parser->state.name);
618 err = EBADKEY;
622 /* Okay, we're all done, with either an error or success; call the parsers
623 to indicate which one. */
625 if (err)
627 /* Maybe print an error message. */
628 if (err == EBADKEY)
629 /* An appropriate message describing what the error was should have
630 been printed earlier. */
631 argp_state_help (&parser->state, parser->state.err_stream,
632 ARGP_HELP_STD_ERR);
634 /* Since we didn't exit, give each parser an error indication. */
635 for (group = parser->groups; group < parser->egroup; group++)
636 group_parse (group, &parser->state, ARGP_KEY_ERROR, 0);
638 else
639 /* Notify parsers of success, and propagate back values from parsers. */
641 /* We pass over the groups in reverse order so that child groups are
642 given a chance to do there processing before passing back a value to
643 the parent. */
644 for (group = parser->egroup - 1
645 ; group >= parser->groups && (!err || err == EBADKEY)
646 ; group--)
647 err = group_parse (group, &parser->state, ARGP_KEY_SUCCESS, 0);
648 if (err == EBADKEY)
649 err = 0; /* Some parser didn't understand. */
652 /* Call parsers once more, to do any final cleanup. Errors are ignored. */
653 for (group = parser->egroup - 1; group >= parser->groups; group--)
654 group_parse (group, &parser->state, ARGP_KEY_FINI, 0);
656 if (err == EBADKEY)
657 err = EINVAL;
659 free (parser->storage);
661 return err;
664 /* Call the user parsers to parse the non-option argument VAL, at the current
665 position, returning any error. The state NEXT pointer is assumed to have
666 been adjusted (by getopt) to point after this argument; this function will
667 adjust it correctly to reflect however many args actually end up being
668 consumed. */
669 static error_t
670 parser_parse_arg (struct parser *parser, char *val)
672 /* Save the starting value of NEXT, first adjusting it so that the arg
673 we're parsing is again the front of the arg vector. */
674 int index = --parser->state.next;
675 error_t err = EBADKEY;
676 struct group *group;
677 int key = 0; /* Which of ARGP_KEY_ARG[S] we used. */
679 /* Try to parse the argument in each parser. */
680 for (group = parser->groups
681 ; group < parser->egroup && err == EBADKEY
682 ; group++)
684 parser->state.next++; /* For ARGP_KEY_ARG, consume the arg. */
685 key = ARGP_KEY_ARG;
686 err = group_parse (group, &parser->state, key, val);
688 if (err == EBADKEY)
689 /* This parser doesn't like ARGP_KEY_ARG; try ARGP_KEY_ARGS instead. */
691 parser->state.next--; /* For ARGP_KEY_ARGS, put back the arg. */
692 key = ARGP_KEY_ARGS;
693 err = group_parse (group, &parser->state, key, 0);
697 if (! err)
699 if (key == ARGP_KEY_ARGS)
700 /* The default for ARGP_KEY_ARGS is to assume that if NEXT isn't
701 changed by the user, *all* arguments should be considered
702 consumed. */
703 parser->state.next = parser->state.argc;
705 if (parser->state.next > index)
706 /* Remember that we successfully processed a non-option
707 argument -- but only if the user hasn't gotten tricky and set
708 the clock back. */
709 (--group)->args_processed += (parser->state.next - index);
710 else
711 /* The user wants to reparse some args, give getopt another try. */
712 parser->try_getopt = 1;
715 return err;
718 /* Call the user parsers to parse the option OPT, with argument VAL, at the
719 current position, returning any error. */
720 static error_t
721 parser_parse_opt (struct parser *parser, int opt, char *val)
723 /* The group key encoded in the high bits; 0 for short opts or
724 group_number + 1 for long opts. */
725 int group_key = opt >> USER_BITS;
726 error_t err = EBADKEY;
728 if (group_key == 0)
729 /* A short option. By comparing OPT's position in SHORT_OPTS to the
730 various starting positions in each group's SHORT_END field, we can
731 determine which group OPT came from. */
733 struct group *group;
734 char *short_index = strchr (parser->short_opts, opt);
736 if (short_index)
737 for (group = parser->groups; group < parser->egroup; group++)
738 if (group->short_end > short_index)
740 err = group_parse (group, &parser->state, opt,
741 parser->opt_data.optarg);
742 break;
745 else
746 /* A long option. We use shifts instead of masking for extracting
747 the user value in order to preserve the sign. */
748 err =
749 group_parse (&parser->groups[group_key - 1], &parser->state,
750 (opt << GROUP_BITS) >> GROUP_BITS,
751 parser->opt_data.optarg);
753 if (err == EBADKEY)
754 /* At least currently, an option not recognized is an error in the
755 parser, because we pre-compute which parser is supposed to deal
756 with each option. */
758 static const char bad_key_err[] =
759 N_("(PROGRAM ERROR) Option should have been recognized!?");
760 if (group_key == 0)
761 argp_error (&parser->state, "-%c: %s", opt,
762 dgettext (parser->argp->argp_domain, bad_key_err));
763 else
765 struct option *long_opt = parser->long_opts;
766 while (long_opt->val != opt && long_opt->name)
767 long_opt++;
768 argp_error (&parser->state, "--%s: %s",
769 long_opt->name ? long_opt->name : "???",
770 dgettext (parser->argp->argp_domain, bad_key_err));
774 return err;
777 /* Parse the next argument in PARSER (as indicated by PARSER->state.next).
778 Any error from the parsers is returned, and *ARGP_EBADKEY indicates
779 whether a value of EBADKEY is due to an unrecognized argument (which is
780 generally not fatal). */
781 static error_t
782 parser_parse_next (struct parser *parser, int *arg_ebadkey)
784 int opt;
785 error_t err = 0;
787 if (parser->state.quoted && parser->state.next < parser->state.quoted)
788 /* The next argument pointer has been moved to before the quoted
789 region, so pretend we never saw the quoting `--', and give getopt
790 another chance. If the user hasn't removed it, getopt will just
791 process it again. */
792 parser->state.quoted = 0;
794 if (parser->try_getopt && !parser->state.quoted)
795 /* Give getopt a chance to parse this. */
797 /* Put it back in OPTIND for getopt. */
798 parser->opt_data.optind = parser->state.next;
799 /* Distinguish KEY_ERR from a real option. */
800 parser->opt_data.optopt = KEY_END;
801 if (parser->state.flags & ARGP_LONG_ONLY)
802 opt = _getopt_long_only_r (parser->state.argc, parser->state.argv,
803 parser->short_opts, parser->long_opts, 0,
804 &parser->opt_data);
805 else
806 opt = _getopt_long_r (parser->state.argc, parser->state.argv,
807 parser->short_opts, parser->long_opts, 0,
808 &parser->opt_data);
809 /* And see what getopt did. */
810 parser->state.next = parser->opt_data.optind;
812 if (opt == KEY_END)
813 /* Getopt says there are no more options, so stop using
814 getopt; we'll continue if necessary on our own. */
816 parser->try_getopt = 0;
817 if (parser->state.next > 1
818 && strcmp (parser->state.argv[parser->state.next - 1], QUOTE)
819 == 0)
820 /* Not only is this the end of the options, but it's a
821 `quoted' region, which may have args that *look* like
822 options, so we definitely shouldn't try to use getopt past
823 here, whatever happens. */
824 parser->state.quoted = parser->state.next;
826 else if (opt == KEY_ERR && parser->opt_data.optopt != KEY_END)
827 /* KEY_ERR can have the same value as a valid user short
828 option, but in the case of a real error, getopt sets OPTOPT
829 to the offending character, which can never be KEY_END. */
831 *arg_ebadkey = 0;
832 return EBADKEY;
835 else
836 opt = KEY_END;
838 if (opt == KEY_END)
840 /* We're past what getopt considers the options. */
841 if (parser->state.next >= parser->state.argc
842 || (parser->state.flags & ARGP_NO_ARGS))
843 /* Indicate that we're done. */
845 *arg_ebadkey = 1;
846 return EBADKEY;
848 else
849 /* A non-option arg; simulate what getopt might have done. */
851 opt = KEY_ARG;
852 parser->opt_data.optarg = parser->state.argv[parser->state.next++];
856 if (opt == KEY_ARG)
857 /* A non-option argument; try each parser in turn. */
858 err = parser_parse_arg (parser, parser->opt_data.optarg);
859 else
860 err = parser_parse_opt (parser, opt, parser->opt_data.optarg);
862 if (err == EBADKEY)
863 *arg_ebadkey = (opt == KEY_END || opt == KEY_ARG);
865 return err;
868 /* Parse the options strings in ARGC & ARGV according to the argp in ARGP.
869 FLAGS is one of the ARGP_ flags above. If END_INDEX is non-NULL, the
870 index in ARGV of the first unparsed option is returned in it. If an
871 unknown option is present, EINVAL is returned; if some parser routine
872 returned a non-zero value, it is returned; otherwise 0 is returned. */
873 error_t
874 argp_parse (const struct argp *argp, int argc, char **argv, unsigned flags,
875 int *end_index, void *input)
877 error_t err;
878 struct parser parser;
880 /* If true, then err == EBADKEY is a result of a non-option argument failing
881 to be parsed (which in some cases isn't actually an error). */
882 int arg_ebadkey = 0;
884 if (! (flags & ARGP_NO_HELP))
885 /* Add our own options. */
887 struct argp_child *child = alloca (4 * sizeof (struct argp_child));
888 struct argp *top_argp = alloca (sizeof (struct argp));
890 /* TOP_ARGP has no options, it just serves to group the user & default
891 argps. */
892 memset (top_argp, 0, sizeof (*top_argp));
893 top_argp->children = child;
895 memset (child, 0, 4 * sizeof (struct argp_child));
897 if (argp)
898 (child++)->argp = argp;
899 (child++)->argp = &argp_default_argp;
900 if (argp_program_version || argp_program_version_hook)
901 (child++)->argp = &argp_version_argp;
902 child->argp = 0;
904 argp = top_argp;
907 /* Construct a parser for these arguments. */
908 err = parser_init (&parser, argp, argc, argv, flags, input);
910 if (! err)
911 /* Parse! */
913 while (! err)
914 err = parser_parse_next (&parser, &arg_ebadkey);
915 err = parser_finalize (&parser, err, arg_ebadkey, end_index);
918 return err;
921 /* Return the input field for ARGP in the parser corresponding to STATE; used
922 by the help routines. */
923 void *
924 __argp_input (const struct argp *argp, const struct argp_state *state)
926 if (state)
928 struct group *group;
929 struct parser *parser = state->pstate;
931 for (group = parser->groups; group < parser->egroup; group++)
932 if (group->argp == argp)
933 return group->input;
936 return 0;