WvStreams
argp-parse.c
00001 /* Hierarchial argument parsing
00002    Copyright (C) 1995, 96, 97, 98, 99, 2000,2003 Free Software Foundation, Inc.
00003    This file is part of the GNU C Library.
00004    Written by Miles Bader <miles@gnu.ai.mit.edu>.
00005 
00006    The GNU C Library is free software; you can redistribute it and/or
00007    modify it under the terms of the GNU Library General Public License as
00008    published by the Free Software Foundation; either version 2 of the
00009    License, or (at your option) any later version.
00010 
00011    The GNU C Library is distributed in the hope that it will be useful,
00012    but WITHOUT ANY WARRANTY; without even the implied warranty of
00013    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00014    Library General Public License for more details.
00015 
00016    You should have received a copy of the GNU Library General Public
00017    License along with the GNU C Library; see the file COPYING.LIB.  If not,
00018    write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
00019    Boston, MA 02111-1307, USA.  */
00020 
00021 #ifndef _GNU_SOURCE
00022 # define _GNU_SOURCE    1
00023 #endif
00024 
00025 #ifdef HAVE_CONFIG_H
00026 #include <config.h>
00027 #endif
00028 
00029 /* AIX requires this to be the first thing in the file.  */
00030 #ifndef __GNUC__
00031 # if HAVE_ALLOCA_H
00032 #  include <alloca.h>
00033 # else
00034 #  ifdef _AIX
00035  #pragma alloca
00036 #  else
00037 #   ifndef alloca /* predefined by HP cc +Olibcalls */
00038 char *alloca ();
00039 #   endif
00040 #  endif
00041 # endif
00042 #endif
00043 
00044 #include <stdlib.h>
00045 #include <string.h>
00046 #include <unistd.h>
00047 #include <limits.h>
00048 #include <assert.h>
00049 #ifdef _WIN32
00050 #include <malloc.h>
00051 #endif
00052 
00053 #ifndef _
00054 /* This is for other GNU distributions with internationalized messages.
00055    When compiling libc, the _ macro is predefined.  */
00056 # if defined HAVE_LIBINTL_H || defined _LIBC
00057 #  include <libintl.h>
00058 #  ifdef _LIBC
00059 #   undef dgettext
00060 #   define dgettext(domain, msgid) __dcgettext (domain, msgid, LC_MESSAGES)
00061 #  endif
00062 # else
00063 #  define dgettext(domain, msgid) (msgid)
00064 #  define gettext(msgid) (msgid)
00065 # endif
00066 #endif
00067 #ifndef N_
00068 # define N_(msgid) (msgid)
00069 #endif
00070 
00071 #if _LIBC - 0
00072 #include <bits/libc-lock.h>
00073 #else
00074 #ifdef HAVE_CTHREADS_H
00075 #include <cthreads.h>
00076 #endif
00077 #endif /* _LIBC */
00078 
00079 #include "argp.h"
00080 #include "argp-namefrob.h"
00081 
00082 
00083 /* The meta-argument used to prevent any further arguments being interpreted
00084    as options.  */
00085 #define QUOTE "--"
00086 
00087 /* EZ alias for ARGP_ERR_UNKNOWN.  */
00088 #define EBADKEY ARGP_ERR_UNKNOWN
00089 
00090 
00091 /* Default options.  */
00092 
00093 /* When argp is given the --HANG switch, _ARGP_HANG is set and argp will sleep
00094    for one second intervals, decrementing _ARGP_HANG until it's zero.  Thus
00095    you can force the program to continue by attaching a debugger and setting
00096    it to 0 yourself.  */
00097 volatile int _argp_hang;
00098 
00099 #define OPT_PROGNAME    -2
00100 #define OPT_USAGE       -3
00101 #define OPT_HANG        -4
00102 
00103 static const struct argp_option argp_default_options[] =
00104 {
00105   {"help",        '?',          0, 0,  N_("Give this help list"), -1},
00106   {"usage",       OPT_USAGE,    0, 0,  N_("Give a short usage message"), 0 },
00107   {"program-name",OPT_PROGNAME,"NAME", OPTION_HIDDEN,
00108      N_("Set the program name"), 0},
00109   {"HANG",        OPT_HANG,    "SECS", OPTION_ARG_OPTIONAL | OPTION_HIDDEN,
00110      N_("Hang for SECS seconds (default 3600)"), 0 },
00111   {0, 0, 0, 0, 0, 0}
00112 };
00113 
00114 static error_t
00115 argp_default_parser (int key, char *arg, struct argp_state *state)
00116 {
00117   switch (key)
00118     {
00119     case '?':
00120       __argp_state_help (state, state->out_stream, ARGP_HELP_STD_HELP);
00121       break;
00122     case OPT_USAGE:
00123       __argp_state_help (state, state->out_stream,
00124                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_OK);
00125       break;
00126 
00127     case OPT_PROGNAME:          /* Set the program name.  */
00128 #if HAVE_DECL_PROGRAM_INVOCATION_NAME
00129       program_invocation_name = arg;
00130 #endif
00131       /* [Note that some systems only have PROGRAM_INVOCATION_SHORT_NAME (aka
00132          __PROGNAME), in which case, PROGRAM_INVOCATION_NAME is just defined
00133          to be that, so we have to be a bit careful here.]  */
00134 
00135       /* Update what we use for messages.  */
00136 
00137       state->name = __argp_basename(arg);
00138       
00139 #if HAVE_DECL_PROGRAM_INVOCATION_SHORT_NAME
00140       program_invocation_short_name = state->name;
00141 #endif
00142 
00143       if ((state->flags & (ARGP_PARSE_ARGV0 | ARGP_NO_ERRS))
00144           == ARGP_PARSE_ARGV0)
00145         /* Update what getopt uses too.  */
00146         state->argv[0] = arg;
00147 
00148       break;
00149 
00150     case OPT_HANG:
00151       _argp_hang = atoi (arg ? arg : "3600");
00152       fprintf(state->err_stream, "%s: pid = %ld\n",
00153               state->name, (long) getpid());
00154       while (_argp_hang-- > 0)
00155         __sleep(1);
00156       break;
00157 
00158     default:
00159       return EBADKEY;
00160     }
00161   return 0;
00162 }
00163 
00164 static const struct argp argp_default_argp =
00165   {argp_default_options, &argp_default_parser, NULL, NULL, NULL, NULL, "libc"};
00166 
00167 
00168 static const struct argp_option argp_version_options[] =
00169 {
00170   {"version",     'V',          0, 0,  N_("Print program version"), -1},
00171   {0, 0, 0, 0, 0, 0 }
00172 };
00173 
00174 static error_t
00175 argp_version_parser (int key, char *arg UNUSED, struct argp_state *state)
00176 {
00177   switch (key)
00178     {
00179     case 'V':
00180       if (argp_program_version_hook)
00181         (*argp_program_version_hook) (state->out_stream, state);
00182       else if (argp_program_version)
00183         fprintf (state->out_stream, "%s\n", argp_program_version);
00184       else
00185         __argp_error (state, dgettext (state->root_argp->argp_domain,
00186                                        "(PROGRAM ERROR) No version known!?"));
00187       if (! (state->flags & ARGP_NO_EXIT))
00188         exit (0);
00189       break;
00190     default:
00191       return EBADKEY;
00192     }
00193   return 0;
00194 }
00195 
00196 static const struct argp argp_version_argp =
00197   {argp_version_options, &argp_version_parser, NULL, NULL, NULL, NULL, "libc"};
00198 
00199 
00200 
00201 /* The state of a `group' during parsing.  Each group corresponds to a
00202    particular argp structure from the tree of such descending from the top
00203    level argp passed to argp_parse.  */
00204 struct group
00205 {
00206   /* This group's parsing function.  */
00207   argp_parser_t parser;
00208 
00209   /* Which argp this group is from.  */
00210   const struct argp *argp;
00211 
00212   /* The number of non-option args sucessfully handled by this parser.  */
00213   unsigned args_processed;
00214 
00215   /* This group's parser's parent's group.  */
00216   struct group *parent;
00217   unsigned parent_index;        /* And the our position in the parent.   */
00218 
00219   /* These fields are swapped into and out of the state structure when
00220      calling this group's parser.  */
00221   void *input, **child_inputs;
00222   void *hook;
00223 };
00224 
00225 /* Call GROUP's parser with KEY and ARG, swapping any group-specific info
00226    from STATE before calling, and back into state afterwards.  If GROUP has
00227    no parser, EBADKEY is returned.  */
00228 static error_t
00229 group_parse (struct group *group, struct argp_state *state, int key, char *arg)
00230 {
00231   if (group->parser)
00232     {
00233       error_t err;
00234       state->hook = group->hook;
00235       state->input = group->input;
00236       state->child_inputs = group->child_inputs;
00237       state->arg_num = group->args_processed;
00238       err = (*group->parser)(key, arg, state);
00239       group->hook = state->hook;
00240       return err;
00241     }
00242   else
00243     return EBADKEY;
00244 }
00245 
00246 struct parser
00247 {
00248   const struct argp *argp;
00249 
00250   const char *posixly_correct;
00251   
00252   /* True if there are only no-option arguments left, which are just
00253      passed verbatim with ARGP_KEY_ARG. This is set if we encounter a
00254      quote, or the end of the proper options, but may be cleared again
00255      if the user moves the next argument pointer backwards. */
00256   int args_only;
00257 
00258   /* Describe how to deal with options that follow non-option ARGV-elements.
00259 
00260      If the caller did not specify anything, the default is
00261      REQUIRE_ORDER if the environment variable POSIXLY_CORRECT is
00262      defined, PERMUTE otherwise.
00263 
00264      REQUIRE_ORDER means don't recognize them as options; stop option
00265      processing when the first non-option is seen. This is what Unix
00266      does. This mode of operation is selected by either setting the
00267      environment variable POSIXLY_CORRECT, or using `+' as the first
00268      character of the list of option characters.
00269 
00270      PERMUTE is the default. We permute the contents of ARGV as we
00271      scan, so that eventually all the non-options are at the end. This
00272      allows options to be given in any order, even with programs that
00273      were not written to expect this.
00274 
00275      RETURN_IN_ORDER is an option available to programs that were
00276      written to expect options and other ARGV-elements in any order
00277      and that care about the ordering of the two. We describe each
00278      non-option ARGV-element as if it were the argument of an option
00279      with character code 1. Using `-' as the first character of the
00280      list of option characters selects this mode of operation.
00281 
00282   */
00283   enum { REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER } ordering;
00284 
00285   /* A segment of non-option arguments that have been skipped for
00286      later processing, after all options. `first_nonopt' is the index
00287      in ARGV of the first of them; `last_nonopt' is the index after
00288      the last of them.
00289 
00290      If quoted or args_only is non-zero, this segment should be empty. */
00291 
00292   /* FIXME: I'd prefer to use unsigned, but it's more consistent to
00293      use the same type as for state.next. */
00294   int first_nonopt;
00295   int last_nonopt;
00296   
00297   /* String of all recognized short options. Needed for ARGP_LONG_ONLY. */
00298   /* FIXME: Perhaps change to a pointer to a suitable bitmap instead? */
00299   char *short_opts;
00300 
00301   /* For parsing combined short options. */
00302   char *nextchar;
00303   
00304   /* States of the various parsing groups.  */
00305   struct group *groups;
00306   /* The end of the GROUPS array.  */
00307   struct group *egroup;
00308   /* An vector containing storage for the CHILD_INPUTS field in all groups.  */
00309   void **child_inputs;
00310   
00311   /* State block supplied to parsing routines.  */
00312   struct argp_state state;
00313 
00314   /* Memory used by this parser.  */
00315   void *storage;
00316 };
00317 
00318 /* Search for a group defining a short option. */
00319 static const struct argp_option *
00320 find_short_option(struct parser *parser, int key, struct group **p)
00321 {
00322   struct group *group;
00323   
00324   assert(key >= 0);
00325   assert(isascii(key));
00326 
00327   for (group = parser->groups; group < parser->egroup; group++)
00328     {
00329       const struct argp_option *opts;
00330 
00331       for (opts = group->argp->options; !__option_is_end(opts); opts++)
00332         if (opts->key == key)
00333           {
00334             *p = group;
00335             return opts;
00336           }
00337     }
00338   return NULL;
00339 }
00340 
00341 enum match_result { MATCH_EXACT, MATCH_PARTIAL, MATCH_NO };
00342 
00343 /* If defined, allow complete.el-like abbreviations of long options. */
00344 #ifndef ARGP_COMPLETE
00345 #define ARGP_COMPLETE 0
00346 #endif
00347 
00348 /* Matches an encountern long-option argument ARG against an option NAME.
00349  * ARG is terminated by NUL or '='. */
00350 static enum match_result
00351 match_option(const char *arg, const char *name)
00352 {
00353   unsigned i, j;
00354   for (i = j = 0;; i++, j++)
00355     {
00356       switch(arg[i])
00357         {
00358         case '\0':
00359         case '=':
00360           return name[j] ? MATCH_PARTIAL : MATCH_EXACT;
00361 #if ARGP_COMPLETE
00362         case '-':
00363           while (name[j] != '-')
00364             if (!name[j++])
00365               return MATCH_NO;
00366           break;
00367 #endif
00368         default:
00369           if (arg[i] != name[j])
00370             return MATCH_NO;
00371         }
00372     }
00373 }
00374 
00375 static const struct argp_option *
00376 find_long_option(struct parser *parser,
00377                  const char *arg,
00378                  struct group **p)
00379 {
00380   struct group *group;
00381 
00382   /* Partial match found so far. */
00383   struct group *matched_group = NULL;
00384   const struct argp_option *matched_option = NULL;
00385 
00386   /* Number of partial matches. */
00387   int num_partial = 0;
00388 
00389   for (group = parser->groups; group < parser->egroup; group++)
00390     {
00391       const struct argp_option *opts;
00392 
00393       for (opts = group->argp->options; !__option_is_end(opts); opts++)
00394         {
00395           if (!opts->name)
00396             continue;
00397           switch (match_option(arg, opts->name))
00398             {
00399             case MATCH_NO:
00400               break;
00401             case MATCH_PARTIAL:
00402               num_partial++;
00403 
00404               matched_group = group;
00405               matched_option = opts;
00406 
00407               break;
00408             case MATCH_EXACT:
00409               /* Exact match. */
00410               *p = group;
00411               return opts;
00412             }
00413         }
00414     }
00415   if (num_partial == 1)
00416     {
00417       *p = matched_group;
00418       return matched_option;
00419     }
00420 
00421   return NULL;
00422 }
00423 
00424 
00425 /* The next usable entries in the various parser tables being filled in by
00426    convert_options.  */
00427 struct parser_convert_state
00428 {
00429   struct parser *parser;
00430   char *short_end;
00431   void **child_inputs_end;
00432 };
00433 
00434 /* Initialize GROUP from ARGP. If CVT->SHORT_END is non-NULL, short
00435    options are recorded in the short options string. Returns the next
00436    unused group entry. CVT holds state used during the conversion. */
00437 static struct group *
00438 convert_options (const struct argp *argp,
00439                  struct group *parent, unsigned parent_index,
00440                  struct group *group, struct parser_convert_state *cvt)
00441 {
00442   const struct argp_option *opt = argp->options;
00443   const struct argp_child *children = argp->children;
00444 
00445   if (opt || argp->parser)
00446     {
00447       /* This parser needs a group. */
00448       if (cvt->short_end)
00449         {
00450           /* Record any short options. */
00451           for ( ; !__option_is_end (opt); opt++)
00452             if (__option_is_short(opt))
00453               *cvt->short_end++ = opt->key;
00454         }
00455       
00456       group->parser = argp->parser;
00457       group->argp = argp;
00458       group->args_processed = 0;
00459       group->parent = parent;
00460       group->parent_index = parent_index;
00461       group->input = 0;
00462       group->hook = 0;
00463       group->child_inputs = 0;
00464       
00465       if (children)
00466         /* Assign GROUP's CHILD_INPUTS field some space from
00467            CVT->child_inputs_end.*/
00468         {
00469           unsigned num_children = 0;
00470           while (children[num_children].argp)
00471             num_children++;
00472           group->child_inputs = cvt->child_inputs_end;
00473           cvt->child_inputs_end += num_children;
00474         }
00475       parent = group++;
00476     }
00477   else
00478     parent = 0;
00479 
00480   if (children)
00481     {
00482       unsigned index = 0;
00483       while (children->argp)
00484         group =
00485           convert_options (children++->argp, parent, index++, group, cvt);
00486     }
00487 
00488   return group;
00489 }
00490 /* Allocate and initialize the group structures, so that they are
00491    ordered as if by traversing the corresponding argp parser tree in
00492    pre-order. Also build the list of short options, if that is needed. */
00493 static void
00494 parser_convert (struct parser *parser, const struct argp *argp)
00495 {
00496   struct parser_convert_state cvt;
00497 
00498   cvt.parser = parser;
00499   cvt.short_end = parser->short_opts;
00500   cvt.child_inputs_end = parser->child_inputs;
00501 
00502   parser->argp = argp;
00503 
00504   if (argp)
00505     parser->egroup = convert_options (argp, 0, 0, parser->groups, &cvt);
00506   else
00507     parser->egroup = parser->groups; /* No parsers at all! */
00508 
00509   if (parser->short_opts)
00510     *cvt.short_end ='\0';
00511 }
00512 
00513 /* Lengths of various parser fields which we will allocated.  */
00514 struct parser_sizes
00515 {
00516   /* Needed only ARGP_LONG_ONLY */
00517   size_t short_len;             /* Number of short options.  */
00518 
00519   size_t num_groups;            /* Group structures we allocate.  */
00520   size_t num_child_inputs;      /* Child input slots.  */
00521 };
00522 
00523 /* For ARGP, increments the NUM_GROUPS field in SZS by the total
00524    number of argp structures descended from it, and the SHORT_LEN by
00525    the total number of short options. */
00526 static void
00527 calc_sizes (const struct argp *argp,  struct parser_sizes *szs)
00528 {
00529   const struct argp_child *child = argp->children;
00530   const struct argp_option *opt = argp->options;
00531 
00532   if (opt || argp->parser)
00533     {
00534       /* This parser needs a group. */
00535       szs->num_groups++;
00536       if (opt)
00537         {
00538           while (__option_is_short (opt++))
00539             szs->short_len++;
00540         }
00541     }
00542 
00543   if (child)
00544     while (child->argp)
00545       {
00546         calc_sizes ((child++)->argp, szs);
00547         szs->num_child_inputs++;
00548       }
00549 }
00550 
00551 /* Initializes PARSER to parse ARGP in a manner described by FLAGS.  */
00552 static error_t
00553 parser_init (struct parser *parser, const struct argp *argp,
00554              int argc, char **argv, int flags, void *input)
00555 {
00556   error_t err = 0;
00557   struct group *group;
00558   struct parser_sizes szs;
00559 
00560   parser->posixly_correct = getenv ("POSIXLY_CORRECT");
00561 
00562   if (flags & ARGP_IN_ORDER)
00563     parser->ordering = RETURN_IN_ORDER;
00564   else if (flags & ARGP_NO_ARGS)
00565     parser->ordering = REQUIRE_ORDER;
00566   else if (parser->posixly_correct)
00567     parser->ordering = REQUIRE_ORDER;
00568   else
00569     parser->ordering = PERMUTE;
00570   
00571   szs.short_len = 0;
00572   szs.num_groups = 0;
00573   szs.num_child_inputs = 0;
00574 
00575   if (argp)
00576     calc_sizes (argp, &szs);
00577 
00578   if (!(flags & ARGP_LONG_ONLY))
00579     /* We have no use for the short option array. */
00580     szs.short_len = 0;
00581   
00582   /* Lengths of the various bits of storage used by PARSER.  */
00583 #define GLEN (szs.num_groups + 1) * sizeof (struct group)
00584 #define CLEN (szs.num_child_inputs * sizeof (void *))
00585 #define SLEN (szs.short_len + 1)
00586 #define STORAGE(offset) ((void *) (((char *) parser->storage) + (offset)))
00587 
00588   parser->storage = malloc (GLEN + CLEN + SLEN);
00589   if (! parser->storage)
00590     return ENOMEM;
00591 
00592   parser->groups = parser->storage;
00593 
00594   parser->child_inputs = STORAGE(GLEN);
00595   memset (parser->child_inputs, 0, szs.num_child_inputs * sizeof (void *));
00596 
00597   if (flags & ARGP_LONG_ONLY)
00598     parser->short_opts = STORAGE(GLEN + CLEN);
00599   else
00600     parser->short_opts = NULL;
00601 
00602   parser_convert (parser, argp);
00603 
00604   memset (&parser->state, 0, sizeof (struct argp_state));
00605   
00606   parser->state.root_argp = parser->argp;
00607   parser->state.argc = argc;
00608   parser->state.argv = argv;
00609   parser->state.flags = flags;
00610   parser->state.err_stream = stderr;
00611   parser->state.out_stream = stdout;
00612   parser->state.pstate = parser;
00613 
00614   parser->args_only = 0;
00615   parser->nextchar = NULL;
00616   parser->first_nonopt = parser->last_nonopt = 0;
00617     
00618   /* Call each parser for the first time, giving it a chance to propagate
00619      values to child parsers.  */
00620   if (parser->groups < parser->egroup)
00621     parser->groups->input = input;
00622   for (group = parser->groups;
00623        group < parser->egroup && (!err || err == EBADKEY);
00624        group++)
00625     {
00626       if (group->parent)
00627         /* If a child parser, get the initial input value from the parent. */
00628         group->input = group->parent->child_inputs[group->parent_index];
00629 
00630       if (!group->parser
00631           && group->argp->children && group->argp->children->argp)
00632         /* For the special case where no parsing function is supplied for an
00633            argp, propagate its input to its first child, if any (this just
00634            makes very simple wrapper argps more convenient).  */
00635         group->child_inputs[0] = group->input;
00636 
00637       err = group_parse (group, &parser->state, ARGP_KEY_INIT, 0);
00638     }
00639   if (err == EBADKEY)
00640     err = 0;                    /* Some parser didn't understand.  */
00641 
00642   if (err)
00643     return err;
00644 
00645   if (argv[0] && !(parser->state.flags & ARGP_PARSE_ARGV0))
00646     /* There's an argv[0]; use it for messages.  */
00647     {
00648       parser->state.name = __argp_basename(argv[0]);
00649 
00650       /* Don't parse it as an argument. */
00651       parser->state.next = 1;
00652     }
00653   else
00654     parser->state.name = __argp_short_program_name(NULL);
00655   
00656   return 0;
00657 }
00658 
00659 /* Free any storage consumed by PARSER (but not PARSER itself).  */
00660 static error_t
00661 parser_finalize (struct parser *parser,
00662                  error_t err, int arg_ebadkey, int *end_index)
00663 {
00664   struct group *group;
00665 
00666   if (err == EBADKEY && arg_ebadkey)
00667     /* Suppress errors generated by unparsed arguments.  */
00668     err = 0;
00669 
00670   if (! err)
00671     {
00672       if (parser->state.next == parser->state.argc)
00673         /* We successfully parsed all arguments!  Call all the parsers again,
00674            just a few more times... */
00675         {
00676           for (group = parser->groups;
00677                group < parser->egroup && (!err || err==EBADKEY);
00678                group++)
00679             if (group->args_processed == 0)
00680               err = group_parse (group, &parser->state, ARGP_KEY_NO_ARGS, 0);
00681           for (group = parser->egroup - 1;
00682                group >= parser->groups && (!err || err==EBADKEY);
00683                group--)
00684             err = group_parse (group, &parser->state, ARGP_KEY_END, 0);
00685 
00686           if (err == EBADKEY)
00687             err = 0;            /* Some parser didn't understand.  */
00688 
00689           /* Tell the user that all arguments are parsed.  */
00690           if (end_index)
00691             *end_index = parser->state.next;
00692         }
00693       else if (end_index)
00694         /* Return any remaining arguments to the user.  */
00695         *end_index = parser->state.next;
00696       else
00697         /* No way to return the remaining arguments, they must be bogus. */
00698         {
00699           if (!(parser->state.flags & ARGP_NO_ERRS)
00700               && parser->state.err_stream)
00701             fprintf (parser->state.err_stream,
00702                      dgettext (parser->argp->argp_domain,
00703                                "%s: Too many arguments\n"),
00704                      parser->state.name);
00705           err = EBADKEY;
00706         }
00707     }
00708 
00709   /* Okay, we're all done, with either an error or success; call the parsers
00710      to indicate which one.  */
00711 
00712   if (err)
00713     {
00714       /* Maybe print an error message.  */
00715       if (err == EBADKEY)
00716         /* An appropriate message describing what the error was should have
00717            been printed earlier.  */
00718         __argp_state_help (&parser->state, parser->state.err_stream,
00719                            ARGP_HELP_STD_ERR);
00720 
00721       /* Since we didn't exit, give each parser an error indication.  */
00722       for (group = parser->groups; group < parser->egroup; group++)
00723         group_parse (group, &parser->state, ARGP_KEY_ERROR, 0);
00724     }
00725   else
00726     /* Notify parsers of success, and propagate back values from parsers.  */
00727     {
00728       /* We pass over the groups in reverse order so that child groups are
00729          given a chance to do there processing before passing back a value to
00730          the parent.  */
00731       for (group = parser->egroup - 1
00732            ; group >= parser->groups && (!err || err == EBADKEY)
00733            ; group--)
00734         err = group_parse (group, &parser->state, ARGP_KEY_SUCCESS, 0);
00735       if (err == EBADKEY)
00736         err = 0;                /* Some parser didn't understand.  */
00737     }
00738 
00739   /* Call parsers once more, to do any final cleanup.  Errors are ignored.  */
00740   for (group = parser->egroup - 1; group >= parser->groups; group--)
00741     group_parse (group, &parser->state, ARGP_KEY_FINI, 0);
00742 
00743   if (err == EBADKEY)
00744     err = EINVAL;
00745 
00746   free (parser->storage);
00747 
00748   return err;
00749 }
00750 
00751 /* Call the user parsers to parse the non-option argument VAL, at the
00752    current position, returning any error. The state NEXT pointer
00753    should point to the argument; this function will adjust it
00754    correctly to reflect however many args actually end up being
00755    consumed. */
00756 static error_t
00757 parser_parse_arg (struct parser *parser, char *val)
00758 {
00759   /* Save the starting value of NEXT */
00760   int index = parser->state.next;
00761   error_t err = EBADKEY;
00762   struct group *group;
00763   int key = 0;                  /* Which of ARGP_KEY_ARG[S] we used.  */
00764 
00765   /* Try to parse the argument in each parser.  */
00766   for (group = parser->groups
00767        ; group < parser->egroup && err == EBADKEY
00768        ; group++)
00769     {
00770       parser->state.next++;     /* For ARGP_KEY_ARG, consume the arg.  */
00771       key = ARGP_KEY_ARG;
00772       err = group_parse (group, &parser->state, key, val);
00773 
00774       if (err == EBADKEY)
00775         /* This parser doesn't like ARGP_KEY_ARG; try ARGP_KEY_ARGS instead. */
00776         {
00777           parser->state.next--; /* For ARGP_KEY_ARGS, put back the arg.  */
00778           key = ARGP_KEY_ARGS;
00779           err = group_parse (group, &parser->state, key, 0);
00780         }
00781     }
00782 
00783   if (! err)
00784     {
00785       if (key == ARGP_KEY_ARGS)
00786         /* The default for ARGP_KEY_ARGS is to assume that if NEXT isn't
00787            changed by the user, *all* arguments should be considered
00788            consumed.  */
00789         parser->state.next = parser->state.argc;
00790 
00791       if (parser->state.next > index)
00792         /* Remember that we successfully processed a non-option
00793            argument -- but only if the user hasn't gotten tricky and set
00794            the clock back.  */
00795         (--group)->args_processed += (parser->state.next - index);
00796       else
00797         /* The user wants to reparse some args, so try looking for options again.  */
00798         parser->args_only = 0;
00799     }
00800 
00801   return err;
00802 }
00803 
00804 /* Exchange two adjacent subsequences of ARGV.
00805    One subsequence is elements [first_nonopt,last_nonopt)
00806    which contains all the non-options that have been skipped so far.
00807    The other is elements [last_nonopt,next), which contains all
00808    the options processed since those non-options were skipped.
00809 
00810    `first_nonopt' and `last_nonopt' are relocated so that they describe
00811    the new indices of the non-options in ARGV after they are moved.  */
00812 
00813 static void
00814 exchange (struct parser *parser)
00815 {
00816   int bottom = parser->first_nonopt;
00817   int middle = parser->last_nonopt;
00818   int top = parser->state.next;
00819   char **argv = parser->state.argv;
00820   
00821   char *tem;
00822 
00823   /* Exchange the shorter segment with the far end of the longer segment.
00824      That puts the shorter segment into the right place.
00825      It leaves the longer segment in the right place overall,
00826      but it consists of two parts that need to be swapped next.  */
00827 
00828   while (top > middle && middle > bottom)
00829     {
00830       if (top - middle > middle - bottom)
00831         {
00832           /* Bottom segment is the short one.  */
00833           int len = middle - bottom;
00834           register int i;
00835 
00836           /* Swap it with the top part of the top segment.  */
00837           for (i = 0; i < len; i++)
00838             {
00839               tem = argv[bottom + i];
00840               argv[bottom + i] = argv[top - (middle - bottom) + i];
00841               argv[top - (middle - bottom) + i] = tem;
00842             }
00843           /* Exclude the moved bottom segment from further swapping.  */
00844           top -= len;
00845         }
00846       else
00847         {
00848           /* Top segment is the short one.  */
00849           int len = top - middle;
00850           register int i;
00851 
00852           /* Swap it with the bottom part of the bottom segment.  */
00853           for (i = 0; i < len; i++)
00854             {
00855               tem = argv[bottom + i];
00856               argv[bottom + i] = argv[middle + i];
00857               argv[middle + i] = tem;
00858             }
00859           /* Exclude the moved top segment from further swapping.  */
00860           bottom += len;
00861         }
00862     }
00863 
00864   /* Update records for the slots the non-options now occupy.  */
00865 
00866   parser->first_nonopt += (parser->state.next - parser->last_nonopt);
00867   parser->last_nonopt = parser->state.next;
00868 }
00869 
00870 
00871 
00872 enum arg_type { ARG_ARG, ARG_SHORT_OPTION,
00873                 ARG_LONG_OPTION, ARG_LONG_ONLY_OPTION,
00874                 ARG_QUOTE };
00875 
00876 static enum arg_type
00877 classify_arg(struct parser *parser, char *arg, char **opt)
00878 {
00879   if (arg[0] == '-')
00880     /* Looks like an option... */
00881     switch (arg[1])
00882       {
00883       case '\0':
00884         /* "-" is not an option. */
00885         return ARG_ARG;
00886       case '-':
00887         /* Long option, or quote. */
00888         if (!arg[2])
00889           return ARG_QUOTE;
00890           
00891         /* A long option. */
00892         if (opt)
00893           *opt = arg + 2;
00894         return ARG_LONG_OPTION;
00895 
00896       default:
00897         /* Short option. But if ARGP_LONG_ONLY, it can also be a long option. */
00898 
00899         if (opt)
00900           *opt = arg + 1;
00901 
00902         if (parser->state.flags & ARGP_LONG_ONLY)
00903           {
00904             /* Rules from getopt.c:
00905 
00906                If long_only and the ARGV-element has the form "-f",
00907                where f is a valid short option, don't consider it an
00908                abbreviated form of a long option that starts with f.
00909                Otherwise there would be no way to give the -f short
00910                option.
00911 
00912                On the other hand, if there's a long option "fubar" and
00913                the ARGV-element is "-fu", do consider that an
00914                abbreviation of the long option, just like "--fu", and
00915                not "-f" with arg "u".
00916 
00917                This distinction seems to be the most useful approach. */
00918 
00919             assert(parser->short_opts);
00920             
00921             if (arg[2] || !strchr(parser->short_opts, arg[1]))
00922               return ARG_LONG_ONLY_OPTION;
00923           }
00924 
00925         return ARG_SHORT_OPTION;
00926       }
00927   
00928   else
00929     return ARG_ARG;
00930 }
00931 
00932 /* Parse the next argument in PARSER (as indicated by PARSER->state.next).
00933    Any error from the parsers is returned, and *ARGP_EBADKEY indicates
00934    whether a value of EBADKEY is due to an unrecognized argument (which is
00935    generally not fatal).  */
00936 static error_t
00937 parser_parse_next (struct parser *parser, int *arg_ebadkey)
00938 {
00939   if (parser->state.quoted && parser->state.next < parser->state.quoted)
00940     /* The next argument pointer has been moved to before the quoted
00941        region, so pretend we never saw the quoting `--', and start
00942        looking for options again. If the `--' is still there we'll just
00943        process it one more time. */
00944     parser->state.quoted = parser->args_only = 0;
00945 
00946   /* Give FIRST_NONOPT & LAST_NONOPT rational values if NEXT has been
00947      moved back by the user (who may also have changed the arguments).  */
00948   if (parser->last_nonopt > parser->state.next)
00949     parser->last_nonopt = parser->state.next;
00950   if (parser->first_nonopt > parser->state.next)
00951     parser->first_nonopt = parser->state.next;
00952 
00953   if (parser->nextchar)
00954     /* Deal with short options. */
00955     {
00956       struct group *group;
00957       char c;
00958       const struct argp_option *option;
00959       char *value = NULL;;
00960 
00961       assert(!parser->args_only);
00962 
00963       c = *parser->nextchar++;
00964       
00965       option = find_short_option(parser, c, &group);
00966       if (!option)
00967         {
00968           if (parser->posixly_correct)
00969             /* 1003.2 specifies the format of this message.  */
00970             fprintf (parser->state.err_stream,
00971                      dgettext(parser->state.root_argp->argp_domain,
00972                               "%s: illegal option -- %c\n"),
00973                      parser->state.name, c);
00974           else
00975             fprintf (parser->state.err_stream,
00976                      dgettext(parser->state.root_argp->argp_domain,
00977                               "%s: invalid option -- %c\n"),
00978                      parser->state.name, c);
00979 
00980           *arg_ebadkey = 0;
00981           return EBADKEY;
00982         }
00983 
00984       if (!*parser->nextchar)
00985         parser->nextchar = NULL;
00986 
00987       if (option->arg)
00988         {
00989           value = parser->nextchar;
00990           parser->nextchar = NULL;
00991               
00992           if (!value
00993               && !(option->flags & OPTION_ARG_OPTIONAL))
00994             /* We need an mandatory argument. */
00995             {
00996               if (parser->state.next == parser->state.argc)
00997                 /* Missing argument */
00998                 {
00999                   /* 1003.2 specifies the format of this message.  */
01000                   fprintf (parser->state.err_stream,
01001                            dgettext(parser->state.root_argp->argp_domain,
01002                                     "%s: option requires an argument -- %c\n"),
01003                            parser->state.name, c);
01004 
01005                   *arg_ebadkey = 0;
01006                   return EBADKEY;
01007                 }
01008               value = parser->state.argv[parser->state.next++];
01009             }
01010         }
01011       return group_parse(group, &parser->state,
01012                          option->key, value);
01013     }
01014   else
01015     /* Advance to the next ARGV-element.  */
01016     {
01017       if (parser->args_only)
01018         {
01019           *arg_ebadkey = 1;
01020           if (parser->state.next >= parser->state.argc)
01021             /* We're done. */
01022             return EBADKEY;
01023           else
01024             return parser_parse_arg(parser,
01025                                     parser->state.argv[parser->state.next]);
01026         }
01027       
01028       if (parser->state.next >= parser->state.argc)
01029         /* Almost done. If there are non-options that we skipped
01030            previously, we should process them now. */
01031         {
01032           *arg_ebadkey = 1;
01033           if (parser->first_nonopt != parser->last_nonopt)
01034             {
01035               exchange(parser);
01036               
01037               /* Start processing the arguments we skipped previously. */
01038               parser->state.next = parser->first_nonopt;
01039               
01040               parser->first_nonopt = parser->last_nonopt = 0;
01041 
01042               parser->args_only = 1;
01043               return 0;
01044             }
01045           else
01046             /* Indicate that we're really done. */
01047             return EBADKEY;
01048         }
01049       else
01050         /* Look for options. */
01051         {
01052           char *arg = parser->state.argv[parser->state.next];
01053 
01054           char *optstart;
01055           enum arg_type token = classify_arg(parser, arg, &optstart);
01056           
01057           switch (token)
01058             {
01059             case ARG_ARG:
01060               switch (parser->ordering)
01061                 {
01062                 case PERMUTE:
01063                   if (parser->first_nonopt == parser->last_nonopt)
01064                     /* Skipped sequence is empty; start a new one. */
01065                     parser->first_nonopt = parser->last_nonopt = parser->state.next;
01066 
01067                   else if (parser->last_nonopt != parser->state.next)
01068                     /* We have a non-empty skipped sequence, and
01069                        we're not at the end-point, so move it. */
01070                     exchange(parser);
01071 
01072                   assert(parser->last_nonopt == parser->state.next);
01073                   
01074                   /* Skip this argument for now. */
01075                   parser->state.next++;
01076                   parser->last_nonopt = parser->state.next; 
01077                   
01078                   return 0;
01079 
01080                 case REQUIRE_ORDER:
01081                   /* Implicit quote before the first argument. */
01082                    parser->args_only = 1;
01083                    return 0;
01084                    
01085                 case RETURN_IN_ORDER:
01086                   *arg_ebadkey = 1;
01087                   return parser_parse_arg(parser, arg);
01088 
01089                 default:
01090                   abort();
01091                 }
01092             case ARG_QUOTE:
01093               /* Skip it, then exchange with any previous non-options. */
01094               parser->state.next++;
01095               assert (parser->last_nonopt != parser->state.next);
01096 
01097               if (parser->first_nonopt != parser->last_nonopt)
01098                 {
01099                   exchange(parser);
01100                   
01101                   /* Start processing the skipped and the quoted
01102                      arguments. */
01103 
01104                   parser->state.quoted = parser->state.next = parser->first_nonopt;
01105 
01106                   /* Also empty the skipped-list, to avoid confusion
01107                      if the user resets the next pointer. */
01108                   parser->first_nonopt = parser->last_nonopt = 0;
01109                 }
01110               else
01111                 parser->state.quoted = parser->state.next;
01112 
01113               parser->args_only = 1;          
01114               return 0;
01115 
01116             case ARG_LONG_ONLY_OPTION:
01117             case ARG_LONG_OPTION:
01118               {
01119                 struct group *group;
01120                 const struct argp_option *option;
01121                 char *value;
01122 
01123                 parser->state.next++;
01124                 option = find_long_option(parser, optstart, &group);
01125                 
01126                 if (!option)
01127                   {
01128                     /* NOTE: This includes any "=something" in the output. */
01129                     fprintf (parser->state.err_stream,
01130                              dgettext(parser->state.root_argp->argp_domain,
01131                                       "%s: unrecognized option `%s'\n"),
01132                              parser->state.name, arg);
01133                     *arg_ebadkey = 0;
01134                     return EBADKEY;
01135                   }
01136 
01137                 value = strchr(optstart, '=');
01138                 if (value)
01139                   value++;
01140                 
01141                 if (value && !option->arg)
01142                   /* Unexpected argument. */
01143                   {
01144                     if (token == ARG_LONG_OPTION)
01145                       /* --option */
01146                       fprintf (parser->state.err_stream,
01147                                dgettext(parser->state.root_argp->argp_domain,
01148                                         "%s: option `--%s' doesn't allow an argument\n"),
01149                                parser->state.name, option->name);
01150                     else
01151                       /* +option or -option */
01152                       fprintf (parser->state.err_stream,
01153                                dgettext(parser->state.root_argp->argp_domain,
01154                                         "%s: option `%c%s' doesn't allow an argument\n"),
01155                                parser->state.name, arg[0], option->name);
01156 
01157                     *arg_ebadkey = 0;
01158                     return EBADKEY;
01159                   }
01160                 
01161                 if (option->arg && !value
01162                     && !(option->flags & OPTION_ARG_OPTIONAL))
01163                   /* We need an mandatory argument. */
01164                   {
01165                     if (parser->state.next == parser->state.argc)
01166                       /* Missing argument */
01167                       {
01168                         if (token == ARG_LONG_OPTION)
01169                           /* --option */
01170                           fprintf (parser->state.err_stream,
01171                                    dgettext(parser->state.root_argp->argp_domain,
01172                                             "%s: option `--%s' requires an argument\n"),
01173                                  parser->state.name, option->name);
01174                         else
01175                           /* +option or -option */
01176                           fprintf (parser->state.err_stream,
01177                                    dgettext(parser->state.root_argp->argp_domain,
01178                                             "%s: option `%c%s' requires an argument\n"),
01179                                    parser->state.name, arg[0], option->name);
01180 
01181                         *arg_ebadkey = 0;
01182                         return EBADKEY;
01183                       }
01184 
01185                     value = parser->state.argv[parser->state.next++];
01186                   }
01187                 *arg_ebadkey = 0;
01188                 return group_parse(group, &parser->state,
01189                                    option->key, value);
01190               }
01191             case ARG_SHORT_OPTION:
01192               parser->state.next++;
01193               parser->nextchar = optstart;
01194               return 0;
01195 
01196             default:
01197               abort();
01198             }
01199         }
01200     }
01201 }
01202 
01203 /* Parse the options strings in ARGC & ARGV according to the argp in ARGP.
01204    FLAGS is one of the ARGP_ flags above.  If END_INDEX is non-NULL, the
01205    index in ARGV of the first unparsed option is returned in it.  If an
01206    unknown option is present, EINVAL is returned; if some parser routine
01207    returned a non-zero value, it is returned; otherwise 0 is returned.  */
01208 error_t
01209 __argp_parse (const struct argp *argp, int argc, char **argv, unsigned flags,
01210               int *end_index, void *input)
01211 {
01212   error_t err;
01213   struct parser parser;
01214 
01215   /* If true, then err == EBADKEY is a result of a non-option argument failing
01216      to be parsed (which in some cases isn't actually an error).  */
01217   int arg_ebadkey = 0;
01218 
01219   if (! (flags & ARGP_NO_HELP))
01220     /* Add our own options.  */
01221     {
01222       struct argp_child *child = alloca (4 * sizeof (struct argp_child));
01223       struct argp *top_argp = alloca (sizeof (struct argp));
01224 
01225       /* TOP_ARGP has no options, it just serves to group the user & default
01226          argps.  */
01227       memset (top_argp, 0, sizeof (*top_argp));
01228       top_argp->children = child;
01229 
01230       memset (child, 0, 4 * sizeof (struct argp_child));
01231 
01232       if (argp)
01233         (child++)->argp = argp;
01234       (child++)->argp = &argp_default_argp;
01235       if (argp_program_version || argp_program_version_hook)
01236         (child++)->argp = &argp_version_argp;
01237       child->argp = 0;
01238 
01239       argp = top_argp;
01240     }
01241 
01242   /* Construct a parser for these arguments.  */
01243   err = parser_init (&parser, argp, argc, argv, flags, input);
01244 
01245   if (! err)
01246     /* Parse! */
01247     {
01248       while (! err)
01249         err = parser_parse_next (&parser, &arg_ebadkey);
01250       err = parser_finalize (&parser, err, arg_ebadkey, end_index);
01251     }
01252 
01253   return err;
01254 }
01255 #ifdef weak_alias
01256 weak_alias (__argp_parse, argp_parse)
01257 #endif
01258 
01259 /* Return the input field for ARGP in the parser corresponding to STATE; used
01260    by the help routines.  */
01261 void *
01262 __argp_input (const struct argp *argp, const struct argp_state *state)
01263 {
01264   if (state)
01265     {
01266       struct group *group;
01267       struct parser *parser = state->pstate;
01268 
01269       for (group = parser->groups; group < parser->egroup; group++)
01270         if (group->argp == argp)
01271           return group->input;
01272     }
01273 
01274   return 0;
01275 }
01276 #ifdef weak_alias
01277 weak_alias (__argp_input, _argp_input)
01278 #endif
01279 
01280 /* Defined here, in case a user is not inlining the definitions in
01281  * argp.h */
01282 void
01283 __argp_usage (__const struct argp_state *__state)
01284 {
01285   __argp_state_help (__state, stderr, ARGP_HELP_STD_USAGE);
01286 }
01287 
01288 int
01289 __option_is_short (__const struct argp_option *__opt)
01290 {
01291   if (__opt->flags & OPTION_DOC)
01292     return 0;
01293   else
01294     {
01295       int __key = __opt->key;
01296       /* FIXME: whether or not a particular key implies a short option
01297        * ought not to be locale dependent. */
01298       return __key > 0 && isprint (__key);
01299     }
01300 }
01301 
01302 int
01303 __option_is_end (__const struct argp_option *__opt)
01304 {
01305   return !__opt->key && !__opt->name && !__opt->doc && !__opt->group;
01306 }