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