Use a consistent style for including <config.h>.
[gnulib.git] / lib / argp-parse.c
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@gnu.ai.mit.edu>.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2, or (at your option)
9    any later version.
10
11    This program 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
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License along
17    with this program; if not, write to the Free Software Foundation,
18    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
19
20 #ifdef HAVE_CONFIG_H
21 # include <config.h>
22 #endif
23
24 #include <alloca.h>
25 #include <stddef.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <unistd.h>
29 #include <limits.h>
30 #include <getopt.h>
31 #include <getopt_int.h>
32
33 #ifdef _LIBC
34 # include <libintl.h>
35 # undef dgettext
36 # define dgettext(domain, msgid) \
37    INTUSE(__dcgettext) (domain, msgid, LC_MESSAGES)
38 #else
39 # include "gettext.h"
40 #endif
41 #define N_(msgid) msgid
42
43 #include "argp.h"
44 #include "argp-namefrob.h"
45
46 #define alignof(type) offsetof (struct { char c; type x; }, x)
47 #define alignto(n, d) ((((n) + (d) - 1) / (d)) * (d))
48
49 /* Getopt return values.  */
50 #define KEY_END (-1)            /* The end of the options.  */
51 #define KEY_ARG 1               /* A non-option argument.  */
52 #define KEY_ERR '?'             /* An error parsing the options.  */
53
54 /* The meta-argument used to prevent any further arguments being interpreted
55    as options.  */
56 #define QUOTE "--"
57
58 /* The number of bits we steal in a long-option value for our own use.  */
59 #define GROUP_BITS CHAR_BIT
60
61 /* The number of bits available for the user value.  */
62 #define USER_BITS ((sizeof ((struct option *)0)->val * CHAR_BIT) - GROUP_BITS)
63 #define USER_MASK ((1 << USER_BITS) - 1)
64
65 /* EZ alias for ARGP_ERR_UNKNOWN.  */
66 #define EBADKEY ARGP_ERR_UNKNOWN
67 \f
68 /* Default options.  */
69
70 /* When argp is given the --HANG switch, _ARGP_HANG is set and argp will sleep
71    for one second intervals, decrementing _ARGP_HANG until it's zero.  Thus
72    you can force the program to continue by attaching a debugger and setting
73    it to 0 yourself.  */
74 static volatile int _argp_hang;
75
76 #define OPT_PROGNAME    -2
77 #define OPT_USAGE       -3
78 #define OPT_HANG        -4
79
80 static const struct argp_option argp_default_options[] =
81 {
82   {"help",        '?',          0, 0,  N_("Give this help list"), -1},
83   {"usage",       OPT_USAGE,    0, 0,  N_("Give a short usage message"), 0},
84   {"program-name",OPT_PROGNAME,"NAME", OPTION_HIDDEN, N_("Set the program name"), 0},
85   {"HANG",        OPT_HANG,    "SECS", OPTION_ARG_OPTIONAL | OPTION_HIDDEN,
86      N_("Hang for SECS seconds (default 3600)"), 0},
87   {NULL, 0, 0, 0, NULL, 0}
88 };
89
90 static error_t
91 argp_default_parser (int key, char *arg, struct argp_state *state)
92 {
93   switch (key)
94     {
95     case '?':
96       __argp_state_help (state, state->out_stream, ARGP_HELP_STD_HELP);
97       break;
98     case OPT_USAGE:
99       __argp_state_help (state, state->out_stream,
100                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_OK);
101       break;
102
103     case OPT_PROGNAME:          /* Set the program name.  */
104 #if defined _LIBC || HAVE_DECL_PROGRAM_INVOCATION_NAME
105       program_invocation_name = arg;
106 #endif
107       /* [Note that some systems only have PROGRAM_INVOCATION_SHORT_NAME (aka
108          __PROGNAME), in which case, PROGRAM_INVOCATION_NAME is just defined
109          to be that, so we have to be a bit careful here.]  */
110
111       /* Update what we use for messages.  */
112       state->name = strrchr (arg, '/');
113       if (state->name)
114         state->name++;
115       else
116         state->name = arg;
117
118 #if defined _LIBC || HAVE_DECL_PROGRAM_INVOCATION_SHORT_NAME
119       program_invocation_short_name = state->name;
120 #endif
121
122       if ((state->flags & (ARGP_PARSE_ARGV0 | ARGP_NO_ERRS))
123           == ARGP_PARSE_ARGV0)
124         /* Update what getopt uses too.  */
125         state->argv[0] = arg;
126
127       break;
128
129     case OPT_HANG:
130       _argp_hang = atoi (arg ? arg : "3600");
131       while (_argp_hang-- > 0)
132         __sleep (1);
133       break;
134
135     default:
136       return EBADKEY;
137     }
138   return 0;
139 }
140
141 static const struct argp argp_default_argp =
142   {argp_default_options, &argp_default_parser, NULL, NULL, NULL, NULL, "libc"};
143
144 \f
145 static const struct argp_option argp_version_options[] =
146 {
147   {"version",     'V',          0, 0,  N_("Print program version"), -1},
148   {NULL, 0, 0, 0, NULL, 0}
149 };
150
151 static error_t
152 argp_version_parser (int key, char *arg, struct argp_state *state)
153 {
154   switch (key)
155     {
156     case 'V':
157       if (argp_program_version_hook)
158         (*argp_program_version_hook) (state->out_stream, state);
159       else if (argp_program_version)
160         fprintf (state->out_stream, "%s\n", argp_program_version);
161       else
162         __argp_error (state, dgettext (state->root_argp->argp_domain,
163                                        "(PROGRAM ERROR) No version known!?"));
164       if (! (state->flags & ARGP_NO_EXIT))
165         exit (0);
166       break;
167     default:
168       return EBADKEY;
169     }
170   return 0;
171 }
172
173 static const struct argp argp_version_argp =
174   {argp_version_options, &argp_version_parser, NULL, NULL, NULL, NULL, "libc"};
175 \f
176 /* Returns the offset into the getopt long options array LONG_OPTIONS of a
177    long option with called NAME, or -1 if none is found.  Passing NULL as
178    NAME will return the number of options.  */
179 static int
180 find_long_option (struct option *long_options, const char *name)
181 {
182   struct option *l = long_options;
183   while (l->name != NULL)
184     if (name != NULL && strcmp (l->name, name) == 0)
185       return l - long_options;
186     else
187       l++;
188   if (name == NULL)
189     return l - long_options;
190   else
191     return -1;
192 }
193
194 \f
195 /* The state of a `group' during parsing.  Each group corresponds to a
196    particular argp structure from the tree of such descending from the top
197    level argp passed to argp_parse.  */
198 struct group
199 {
200   /* This group's parsing function.  */
201   argp_parser_t parser;
202
203   /* Which argp this group is from.  */
204   const struct argp *argp;
205
206   /* Points to the point in SHORT_OPTS corresponding to the end of the short
207      options for this group.  We use it to determine from which group a
208      particular short options is from.  */
209   char *short_end;
210
211   /* The number of non-option args sucessfully handled by this parser.  */
212   unsigned args_processed;
213
214   /* This group's parser's parent's group.  */
215   struct group *parent;
216   unsigned parent_index;        /* And the our position in the parent.   */
217
218   /* These fields are swapped into and out of the state structure when
219      calling this group's parser.  */
220   void *input, **child_inputs;
221   void *hook;
222 };
223
224 /* Call GROUP's parser with KEY and ARG, swapping any group-specific info
225    from STATE before calling, and back into state afterwards.  If GROUP has
226    no parser, EBADKEY is returned.  */
227 static error_t
228 group_parse (struct group *group, struct argp_state *state, int key, char *arg)
229 {
230   if (group->parser)
231     {
232       error_t err;
233       state->hook = group->hook;
234       state->input = group->input;
235       state->child_inputs = group->child_inputs;
236       state->arg_num = group->args_processed;
237       err = (*group->parser)(key, arg, state);
238       group->hook = state->hook;
239       return err;
240     }
241   else
242     return EBADKEY;
243 }
244 \f
245 struct parser
246 {
247   const struct argp *argp;
248
249   /* SHORT_OPTS is the getopt short options string for the union of all the
250      groups of options.  */
251   char *short_opts;
252   /* LONG_OPTS is the array of getop long option structures for the union of
253      all the groups of options.  */
254   struct option *long_opts;
255   /* OPT_DATA is the getopt data used for the re-entrant getopt.  */
256   struct _getopt_data opt_data;
257
258   /* States of the various parsing groups.  */
259   struct group *groups;
260   /* The end of the GROUPS array.  */
261   struct group *egroup;
262   /* An vector containing storage for the CHILD_INPUTS field in all groups.  */
263   void **child_inputs;
264
265   /* True if we think using getopt is still useful; if false, then
266      remaining arguments are just passed verbatim with ARGP_KEY_ARG.  This is
267      cleared whenever getopt returns KEY_END, but may be set again if the user
268      moves the next argument pointer backwards.  */
269   int try_getopt;
270
271   /* State block supplied to parsing routines.  */
272   struct argp_state state;
273
274   /* Memory used by this parser.  */
275   void *storage;
276 };
277 \f
278 /* The next usable entries in the various parser tables being filled in by
279    convert_options.  */
280 struct parser_convert_state
281 {
282   struct parser *parser;
283   char *short_end;
284   struct option *long_end;
285   void **child_inputs_end;
286 };
287
288 /* Converts all options in ARGP (which is put in GROUP) and ancestors
289    into getopt options stored in SHORT_OPTS and LONG_OPTS; SHORT_END and
290    CVT->LONG_END are the points at which new options are added.  Returns the
291    next unused group entry.  CVT holds state used during the conversion.  */
292 static struct group *
293 convert_options (const struct argp *argp,
294                  struct group *parent, unsigned parent_index,
295                  struct group *group, struct parser_convert_state *cvt)
296 {
297   /* REAL is the most recent non-alias value of OPT.  */
298   const struct argp_option *real = argp->options;
299   const struct argp_child *children = argp->children;
300
301   if (real || argp->parser)
302     {
303       const struct argp_option *opt;
304
305       if (real)
306         for (opt = real; !__option_is_end (opt); opt++)
307           {
308             if (! (opt->flags & OPTION_ALIAS))
309               /* OPT isn't an alias, so we can use values from it.  */
310               real = opt;
311
312             if (! (real->flags & OPTION_DOC))
313               /* A real option (not just documentation).  */
314               {
315                 if (__option_is_short (opt))
316                   /* OPT can be used as a short option.  */
317                   {
318                     *cvt->short_end++ = opt->key;
319                     if (real->arg)
320                       {
321                         *cvt->short_end++ = ':';
322                         if (real->flags & OPTION_ARG_OPTIONAL)
323                           *cvt->short_end++ = ':';
324                       }
325                     *cvt->short_end = '\0'; /* keep 0 terminated */
326                   }
327
328                 if (opt->name
329                     && find_long_option (cvt->parser->long_opts, opt->name) < 0)
330                   /* OPT can be used as a long option.  */
331                   {
332                     cvt->long_end->name = opt->name;
333                     cvt->long_end->has_arg =
334                       (real->arg
335                        ? (real->flags & OPTION_ARG_OPTIONAL
336                           ? optional_argument
337                           : required_argument)
338                        : no_argument);
339                     cvt->long_end->flag = 0;
340                     /* we add a disambiguating code to all the user's
341                        values (which is removed before we actually call
342                        the function to parse the value); this means that
343                        the user loses use of the high 8 bits in all his
344                        values (the sign of the lower bits is preserved
345                        however)...  */
346                     cvt->long_end->val =
347                       ((opt->key | real->key) & USER_MASK)
348                       + (((group - cvt->parser->groups) + 1) << USER_BITS);
349
350                     /* Keep the LONG_OPTS list terminated.  */
351                     (++cvt->long_end)->name = NULL;
352                   }
353               }
354             }
355
356       group->parser = argp->parser;
357       group->argp = argp;
358       group->short_end = cvt->short_end;
359       group->args_processed = 0;
360       group->parent = parent;
361       group->parent_index = parent_index;
362       group->input = 0;
363       group->hook = 0;
364       group->child_inputs = 0;
365
366       if (children)
367         /* Assign GROUP's CHILD_INPUTS field some space from
368            CVT->child_inputs_end.*/
369         {
370           unsigned num_children = 0;
371           while (children[num_children].argp)
372             num_children++;
373           group->child_inputs = cvt->child_inputs_end;
374           cvt->child_inputs_end += num_children;
375         }
376
377       parent = group++;
378     }
379   else
380     parent = 0;
381
382   if (children)
383     {
384       unsigned index = 0;
385       while (children->argp)
386         group =
387           convert_options (children++->argp, parent, index++, group, cvt);
388     }
389
390   return group;
391 }
392
393 /* Find the merged set of getopt options, with keys appropiately prefixed. */
394 static void
395 parser_convert (struct parser *parser, const struct argp *argp, int flags)
396 {
397   struct parser_convert_state cvt;
398
399   cvt.parser = parser;
400   cvt.short_end = parser->short_opts;
401   cvt.long_end = parser->long_opts;
402   cvt.child_inputs_end = parser->child_inputs;
403
404   if (flags & ARGP_IN_ORDER)
405     *cvt.short_end++ = '-';
406   else if (flags & ARGP_NO_ARGS)
407     *cvt.short_end++ = '+';
408   *cvt.short_end = '\0';
409
410   cvt.long_end->name = NULL;
411
412   parser->argp = argp;
413
414   if (argp)
415     parser->egroup = convert_options (argp, 0, 0, parser->groups, &cvt);
416   else
417     parser->egroup = parser->groups; /* No parsers at all! */
418 }
419 \f
420 /* Lengths of various parser fields which we will allocated.  */
421 struct parser_sizes
422 {
423   size_t short_len;             /* Getopt short options string.  */
424   size_t long_len;              /* Getopt long options vector.  */
425   size_t num_groups;            /* Group structures we allocate.  */
426   size_t num_child_inputs;      /* Child input slots.  */
427 };
428
429 /* For ARGP, increments the NUM_GROUPS field in SZS by the total number of
430  argp structures descended from it, and the SHORT_LEN & LONG_LEN fields by
431  the maximum lengths of the resulting merged getopt short options string and
432  long-options array, respectively.  */
433 static void
434 calc_sizes (const struct argp *argp,  struct parser_sizes *szs)
435 {
436   const struct argp_child *child = argp->children;
437   const struct argp_option *opt = argp->options;
438
439   if (opt || argp->parser)
440     {
441       szs->num_groups++;
442       if (opt)
443         {
444           int num_opts = 0;
445           while (!__option_is_end (opt++))
446             num_opts++;
447           szs->short_len += num_opts * 3; /* opt + up to 2 `:'s */
448           szs->long_len += num_opts;
449         }
450     }
451
452   if (child)
453     while (child->argp)
454       {
455         calc_sizes ((child++)->argp, szs);
456         szs->num_child_inputs++;
457       }
458 }
459
460 /* Initializes PARSER to parse ARGP in a manner described by FLAGS.  */
461 static error_t
462 parser_init (struct parser *parser, const struct argp *argp,
463              int argc, char **argv, int flags, void *input)
464 {
465   error_t err = 0;
466   struct group *group;
467   struct parser_sizes szs;
468   struct _getopt_data opt_data = _GETOPT_DATA_INITIALIZER;
469   char *storage;
470   size_t glen, gsum;
471   size_t clen, csum;
472   size_t llen, lsum;
473   size_t slen, ssum;
474
475   szs.short_len = (flags & ARGP_NO_ARGS) ? 0 : 1;
476   szs.long_len = 0;
477   szs.num_groups = 0;
478   szs.num_child_inputs = 0;
479
480   if (argp)
481     calc_sizes (argp, &szs);
482
483   /* Lengths of the various bits of storage used by PARSER.  */
484   glen = (szs.num_groups + 1) * sizeof (struct group);
485   clen = szs.num_child_inputs * sizeof (void *);
486   llen = (szs.long_len + 1) * sizeof (struct option);
487   slen = szs.short_len + 1;
488
489   /* Sums of previous lengths, properly aligned.  There's no need to
490      align gsum, since struct group is aligned at least as strictly as
491      void * (since it contains a void * member).  And there's no need
492      to align lsum, since struct option is aligned at least as
493      strictly as char.  */
494   gsum = glen;
495   csum = alignto (gsum + clen, alignof (struct option));
496   lsum = csum + llen;
497   ssum = lsum + slen;
498
499   parser->storage = malloc (ssum);
500   if (! parser->storage)
501     return ENOMEM;
502
503   storage = parser->storage;
504   parser->groups = parser->storage;
505   parser->child_inputs = (void **) (storage + gsum);
506   parser->long_opts = (struct option *) (storage + csum);
507   parser->short_opts = storage + lsum;
508   parser->opt_data = opt_data;
509
510   memset (parser->child_inputs, 0, clen);
511   parser_convert (parser, argp, flags);
512
513   memset (&parser->state, 0, sizeof (struct argp_state));
514   parser->state.root_argp = parser->argp;
515   parser->state.argc = argc;
516   parser->state.argv = argv;
517   parser->state.flags = flags;
518   parser->state.err_stream = stderr;
519   parser->state.out_stream = stdout;
520   parser->state.next = 0;       /* Tell getopt to initialize.  */
521   parser->state.pstate = parser;
522
523   parser->try_getopt = 1;
524
525   /* Call each parser for the first time, giving it a chance to propagate
526      values to child parsers.  */
527   if (parser->groups < parser->egroup)
528     parser->groups->input = input;
529   for (group = parser->groups;
530        group < parser->egroup && (!err || err == EBADKEY);
531        group++)
532     {
533       if (group->parent)
534         /* If a child parser, get the initial input value from the parent. */
535         group->input = group->parent->child_inputs[group->parent_index];
536
537       if (!group->parser
538           && group->argp->children && group->argp->children->argp)
539         /* For the special case where no parsing function is supplied for an
540            argp, propagate its input to its first child, if any (this just
541            makes very simple wrapper argps more convenient).  */
542         group->child_inputs[0] = group->input;
543
544       err = group_parse (group, &parser->state, ARGP_KEY_INIT, 0);
545     }
546   if (err == EBADKEY)
547     err = 0;                    /* Some parser didn't understand.  */
548
549   if (err)
550     return err;
551
552   if (parser->state.flags & ARGP_NO_ERRS)
553     {
554       parser->opt_data.opterr = 0;
555       if (parser->state.flags & ARGP_PARSE_ARGV0)
556         /* getopt always skips ARGV[0], so we have to fake it out.  As long
557            as OPTERR is 0, then it shouldn't actually try to access it.  */
558         parser->state.argv--, parser->state.argc++;
559     }
560   else
561     parser->opt_data.opterr = 1;        /* Print error messages.  */
562
563   if (parser->state.argv == argv && argv[0])
564     /* There's an argv[0]; use it for messages.  */
565     {
566       char *short_name = strrchr (argv[0], '/');
567       parser->state.name = short_name ? short_name + 1 : argv[0];
568     }
569   else
570     parser->state.name = __argp_short_program_name ();
571
572   return 0;
573 }
574 \f
575 /* Free any storage consumed by PARSER (but not PARSER itself).  */
576 static error_t
577 parser_finalize (struct parser *parser,
578                  error_t err, int arg_ebadkey, int *end_index)
579 {
580   struct group *group;
581
582   if (err == EBADKEY && arg_ebadkey)
583     /* Suppress errors generated by unparsed arguments.  */
584     err = 0;
585
586   if (! err)
587     {
588       if (parser->state.next == parser->state.argc)
589         /* We successfully parsed all arguments!  Call all the parsers again,
590            just a few more times... */
591         {
592           for (group = parser->groups;
593                group < parser->egroup && (!err || err==EBADKEY);
594                group++)
595             if (group->args_processed == 0)
596               err = group_parse (group, &parser->state, ARGP_KEY_NO_ARGS, 0);
597           for (group = parser->egroup - 1;
598                group >= parser->groups && (!err || err==EBADKEY);
599                group--)
600             err = group_parse (group, &parser->state, ARGP_KEY_END, 0);
601
602           if (err == EBADKEY)
603             err = 0;            /* Some parser didn't understand.  */
604
605           /* Tell the user that all arguments are parsed.  */
606           if (end_index)
607             *end_index = parser->state.next;
608         }
609       else if (end_index)
610         /* Return any remaining arguments to the user.  */
611         *end_index = parser->state.next;
612       else
613         /* No way to return the remaining arguments, they must be bogus. */
614         {
615           if (!(parser->state.flags & ARGP_NO_ERRS)
616               && parser->state.err_stream)
617             fprintf (parser->state.err_stream,
618                      dgettext (parser->argp->argp_domain,
619                                "%s: Too many arguments\n"),
620                      parser->state.name);
621           err = EBADKEY;
622         }
623     }
624
625   /* Okay, we're all done, with either an error or success; call the parsers
626      to indicate which one.  */
627
628   if (err)
629     {
630       /* Maybe print an error message.  */
631       if (err == EBADKEY)
632         /* An appropriate message describing what the error was should have
633            been printed earlier.  */
634         __argp_state_help (&parser->state, parser->state.err_stream,
635                            ARGP_HELP_STD_ERR);
636
637       /* Since we didn't exit, give each parser an error indication.  */
638       for (group = parser->groups; group < parser->egroup; group++)
639         group_parse (group, &parser->state, ARGP_KEY_ERROR, 0);
640     }
641   else
642     /* Notify parsers of success, and propagate back values from parsers.  */
643     {
644       /* We pass over the groups in reverse order so that child groups are
645          given a chance to do there processing before passing back a value to
646          the parent.  */
647       for (group = parser->egroup - 1
648            ; group >= parser->groups && (!err || err == EBADKEY)
649            ; group--)
650         err = group_parse (group, &parser->state, ARGP_KEY_SUCCESS, 0);
651       if (err == EBADKEY)
652         err = 0;                /* Some parser didn't understand.  */
653     }
654
655   /* Call parsers once more, to do any final cleanup.  Errors are ignored.  */
656   for (group = parser->egroup - 1; group >= parser->groups; group--)
657     group_parse (group, &parser->state, ARGP_KEY_FINI, 0);
658
659   if (err == EBADKEY)
660     err = EINVAL;
661
662   free (parser->storage);
663
664   return err;
665 }
666 \f
667 /* Call the user parsers to parse the non-option argument VAL, at the current
668    position, returning any error.  The state NEXT pointer is assumed to have
669    been adjusted (by getopt) to point after this argument; this function will
670    adjust it correctly to reflect however many args actually end up being
671    consumed.  */
672 static error_t
673 parser_parse_arg (struct parser *parser, char *val)
674 {
675   /* Save the starting value of NEXT, first adjusting it so that the arg
676      we're parsing is again the front of the arg vector.  */
677   int index = --parser->state.next;
678   error_t err = EBADKEY;
679   struct group *group;
680   int key = 0;                  /* Which of ARGP_KEY_ARG[S] we used.  */
681
682   /* Try to parse the argument in each parser.  */
683   for (group = parser->groups
684        ; group < parser->egroup && err == EBADKEY
685        ; group++)
686     {
687       parser->state.next++;     /* For ARGP_KEY_ARG, consume the arg.  */
688       key = ARGP_KEY_ARG;
689       err = group_parse (group, &parser->state, key, val);
690
691       if (err == EBADKEY)
692         /* This parser doesn't like ARGP_KEY_ARG; try ARGP_KEY_ARGS instead. */
693         {
694           parser->state.next--; /* For ARGP_KEY_ARGS, put back the arg.  */
695           key = ARGP_KEY_ARGS;
696           err = group_parse (group, &parser->state, key, 0);
697         }
698     }
699
700   if (! err)
701     {
702       if (key == ARGP_KEY_ARGS)
703         /* The default for ARGP_KEY_ARGS is to assume that if NEXT isn't
704            changed by the user, *all* arguments should be considered
705            consumed.  */
706         parser->state.next = parser->state.argc;
707
708       if (parser->state.next > index)
709         /* Remember that we successfully processed a non-option
710            argument -- but only if the user hasn't gotten tricky and set
711            the clock back.  */
712         (--group)->args_processed += (parser->state.next - index);
713       else
714         /* The user wants to reparse some args, give getopt another try.  */
715         parser->try_getopt = 1;
716     }
717
718   return err;
719 }
720 \f
721 /* Call the user parsers to parse the option OPT, with argument VAL, at the
722    current position, returning any error.  */
723 static error_t
724 parser_parse_opt (struct parser *parser, int opt, char *val)
725 {
726   /* The group key encoded in the high bits; 0 for short opts or
727      group_number + 1 for long opts.  */
728   int group_key = opt >> USER_BITS;
729   error_t err = EBADKEY;
730
731   if (group_key == 0)
732     /* A short option.  By comparing OPT's position in SHORT_OPTS to the
733        various starting positions in each group's SHORT_END field, we can
734        determine which group OPT came from.  */
735     {
736       struct group *group;
737       char *short_index = strchr (parser->short_opts, opt);
738
739       if (short_index)
740         for (group = parser->groups; group < parser->egroup; group++)
741           if (group->short_end > short_index)
742             {
743               err = group_parse (group, &parser->state, opt,
744                                  parser->opt_data.optarg);
745               break;
746             }
747     }
748   else
749     /* A long option.  We use shifts instead of masking for extracting
750        the user value in order to preserve the sign.  */
751     err =
752       group_parse (&parser->groups[group_key - 1], &parser->state,
753                    (opt << GROUP_BITS) >> GROUP_BITS,
754                    parser->opt_data.optarg);
755
756   if (err == EBADKEY)
757     /* At least currently, an option not recognized is an error in the
758        parser, because we pre-compute which parser is supposed to deal
759        with each option.  */
760     {
761       static const char bad_key_err[] =
762         N_("(PROGRAM ERROR) Option should have been recognized!?");
763       if (group_key == 0)
764         __argp_error (&parser->state, "-%c: %s", opt,
765                       dgettext (parser->argp->argp_domain, bad_key_err));
766       else
767         {
768           struct option *long_opt = parser->long_opts;
769           while (long_opt->val != opt && long_opt->name)
770             long_opt++;
771           __argp_error (&parser->state, "--%s: %s",
772                         long_opt->name ? long_opt->name : "???",
773                         dgettext (parser->argp->argp_domain, bad_key_err));
774         }
775     }
776
777   return err;
778 }
779 \f
780 /* Parse the next argument in PARSER (as indicated by PARSER->state.next).
781    Any error from the parsers is returned, and *ARGP_EBADKEY indicates
782    whether a value of EBADKEY is due to an unrecognized argument (which is
783    generally not fatal).  */
784 static error_t
785 parser_parse_next (struct parser *parser, int *arg_ebadkey)
786 {
787   int opt;
788   error_t err = 0;
789
790   if (parser->state.quoted && parser->state.next < parser->state.quoted)
791     /* The next argument pointer has been moved to before the quoted
792        region, so pretend we never saw the quoting `--', and give getopt
793        another chance.  If the user hasn't removed it, getopt will just
794        process it again.  */
795     parser->state.quoted = 0;
796
797   if (parser->try_getopt && !parser->state.quoted)
798     /* Give getopt a chance to parse this.  */
799     {
800       /* Put it back in OPTIND for getopt.  */
801       parser->opt_data.optind = parser->state.next;
802       /* Distinguish KEY_ERR from a real option.  */
803       parser->opt_data.optopt = KEY_END;
804       if (parser->state.flags & ARGP_LONG_ONLY)
805         opt = _getopt_long_only_r (parser->state.argc, parser->state.argv,
806                                    parser->short_opts, parser->long_opts, 0,
807                                    &parser->opt_data);
808       else
809         opt = _getopt_long_r (parser->state.argc, parser->state.argv,
810                               parser->short_opts, parser->long_opts, 0,
811                               &parser->opt_data);
812       /* And see what getopt did.  */
813       parser->state.next = parser->opt_data.optind;
814
815       if (opt == KEY_END)
816         /* Getopt says there are no more options, so stop using
817            getopt; we'll continue if necessary on our own.  */
818         {
819           parser->try_getopt = 0;
820           if (parser->state.next > 1
821               && strcmp (parser->state.argv[parser->state.next - 1], QUOTE)
822                    == 0)
823             /* Not only is this the end of the options, but it's a
824                `quoted' region, which may have args that *look* like
825                options, so we definitely shouldn't try to use getopt past
826                here, whatever happens.  */
827             parser->state.quoted = parser->state.next;
828         }
829       else if (opt == KEY_ERR && parser->opt_data.optopt != KEY_END)
830         /* KEY_ERR can have the same value as a valid user short
831            option, but in the case of a real error, getopt sets OPTOPT
832            to the offending character, which can never be KEY_END.  */
833         {
834           *arg_ebadkey = 0;
835           return EBADKEY;
836         }
837     }
838   else
839     opt = KEY_END;
840
841   if (opt == KEY_END)
842     {
843       /* We're past what getopt considers the options.  */
844       if (parser->state.next >= parser->state.argc
845           || (parser->state.flags & ARGP_NO_ARGS))
846         /* Indicate that we're done.  */
847         {
848           *arg_ebadkey = 1;
849           return EBADKEY;
850         }
851       else
852         /* A non-option arg; simulate what getopt might have done.  */
853         {
854           opt = KEY_ARG;
855           parser->opt_data.optarg = parser->state.argv[parser->state.next++];
856         }
857     }
858
859   if (opt == KEY_ARG)
860     /* A non-option argument; try each parser in turn.  */
861     err = parser_parse_arg (parser, parser->opt_data.optarg);
862   else
863     err = parser_parse_opt (parser, opt, parser->opt_data.optarg);
864
865   if (err == EBADKEY)
866     *arg_ebadkey = (opt == KEY_END || opt == KEY_ARG);
867
868   return err;
869 }
870 \f
871 /* Parse the options strings in ARGC & ARGV according to the argp in ARGP.
872    FLAGS is one of the ARGP_ flags above.  If END_INDEX is non-NULL, the
873    index in ARGV of the first unparsed option is returned in it.  If an
874    unknown option is present, EINVAL is returned; if some parser routine
875    returned a non-zero value, it is returned; otherwise 0 is returned.  */
876 error_t
877 __argp_parse (const struct argp *argp, int argc, char **argv, unsigned flags,
878               int *end_index, void *input)
879 {
880   error_t err;
881   struct parser parser;
882
883   /* If true, then err == EBADKEY is a result of a non-option argument failing
884      to be parsed (which in some cases isn't actually an error).  */
885   int arg_ebadkey = 0;
886
887   if (! (flags & ARGP_NO_HELP))
888     /* Add our own options.  */
889     {
890       struct argp_child *child = alloca (4 * sizeof (struct argp_child));
891       struct argp *top_argp = alloca (sizeof (struct argp));
892
893       /* TOP_ARGP has no options, it just serves to group the user & default
894          argps.  */
895       memset (top_argp, 0, sizeof (*top_argp));
896       top_argp->children = child;
897
898       memset (child, 0, 4 * sizeof (struct argp_child));
899
900       if (argp)
901         (child++)->argp = argp;
902       (child++)->argp = &argp_default_argp;
903       if (argp_program_version || argp_program_version_hook)
904         (child++)->argp = &argp_version_argp;
905       child->argp = 0;
906
907       argp = top_argp;
908     }
909
910   /* Construct a parser for these arguments.  */
911   err = parser_init (&parser, argp, argc, argv, flags, input);
912
913   if (! err)
914     /* Parse! */
915     {
916       while (! err)
917         err = parser_parse_next (&parser, &arg_ebadkey);
918       err = parser_finalize (&parser, err, arg_ebadkey, end_index);
919     }
920
921   return err;
922 }
923 #ifdef weak_alias
924 weak_alias (__argp_parse, argp_parse)
925 #endif
926 \f
927 /* Return the input field for ARGP in the parser corresponding to STATE; used
928    by the help routines.  */
929 void *
930 __argp_input (const struct argp *argp, const struct argp_state *state)
931 {
932   if (state)
933     {
934       struct group *group;
935       struct parser *parser = state->pstate;
936
937       for (group = parser->groups; group < parser->egroup; group++)
938         if (group->argp == argp)
939           return group->input;
940     }
941
942   return 0;
943 }
944 #ifdef weak_alias
945 weak_alias (__argp_input, _argp_input)
946 #endif