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