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