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