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