argp-parse.c

00001 /* Hierarchial argument parsing, layered over getopt
00002    Copyright (C) 1995-2000, 2002, 2003, 2004 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    This program is free software; you can redistribute it and/or modify
00007    it under the terms of the GNU Lesser General Public License as published by
00008    the Free Software Foundation; either version 2.1, or (at your option)
00009    any later version.
00010 
00011    This program 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
00014    GNU Lesser General Public License for more details.
00015 
00016    You should have received a copy of the GNU Lesser General Public License along
00017    with this program; if not, write to the Free Software Foundation,
00018    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
00019 
00020 #ifdef HAVE_CONFIG_H
00021 # include <config.h>
00022 #endif
00023 
00024 //#include <alloca.h>
00025 #include <stddef.h>
00026 #include <stdlib.h>
00027 #include <string.h>
00028 #include <unistd.h>
00029 #include <limits.h>
00030 #include <getopt.h>
00031 #include <getopt_int.h>
00032 
00033 #ifdef _LIBC
00034 # include <libintl.h>
00035 # undef dgettext
00036 # define dgettext(domain, msgid) \
00037    INTUSE(__dcgettext) (domain, msgid, LC_MESSAGES)
00038 #else
00039 # include "gettext.h"
00040 #endif
00041 #define N_(msgid) msgid
00042 
00043 #undef __argc
00044 #undef __argv
00045 #include "argp.h"
00046 #include "argp-namefrob.h"
00047 
00048 #define alignof(type) offsetof (struct { char c; type x; }, x)
00049 #define alignto(n, d) ((((n) + (d) - 1) / (d)) * (d))
00050 
00051 /* Getopt return values.  */
00052 #define KEY_END (-1)            /* The end of the options.  */
00053 #define KEY_ARG 1               /* A non-option argument.  */
00054 #define KEY_ERR '?'             /* An error parsing the options.  */
00055 
00056 /* The meta-argument used to prevent any further arguments being interpreted
00057    as options.  */
00058 #define QUOTE "--"
00059 
00060 /* The number of bits we steal in a long-option value for our own use.  */
00061 #define GROUP_BITS CHAR_BIT
00062 
00063 /* The number of bits available for the user value.  */
00064 #define USER_BITS ((sizeof ((struct option *)0)->val * CHAR_BIT) - GROUP_BITS)
00065 #define USER_MASK ((1 << USER_BITS) - 1)
00066 
00067 /* EZ alias for ARGP_ERR_UNKNOWN.  */
00068 #define EBADKEY ARGP_ERR_UNKNOWN
00069 
00070 /* Default options.  */
00071 
00072 /* When argp is given the --HANG switch, _ARGP_HANG is set and argp will sleep
00073    for one second intervals, decrementing _ARGP_HANG until it's zero.  Thus
00074    you can force the program to continue by attaching a debugger and setting
00075    it to 0 yourself.  */
00076 static volatile int _argp_hang;
00077 
00078 #define OPT_PROGNAME    -2
00079 #define OPT_USAGE       -3
00080 #define OPT_HANG        -4
00081 
00082 static const struct argp_option argp_default_options[] =
00083 {
00084   {"help",        '?',          0, 0,  N_("Give this help list"), -1},
00085   {"usage",       OPT_USAGE,    0, 0,  N_("Give a short usage message"), 0},
00086   {"program-name",OPT_PROGNAME,"NAME", OPTION_HIDDEN, N_("Set the program name"), 0},
00087   {"HANG",        OPT_HANG,    "SECS", OPTION_ARG_OPTIONAL | OPTION_HIDDEN,
00088      N_("Hang for SECS seconds (default 3600)"), 0},
00089   {NULL, 0, 0, 0, NULL, 0}
00090 };
00091 
00092 static error_t
00093 argp_default_parser (int key, char *arg, struct argp_state *state)
00094 {
00095   switch (key)
00096     {
00097     case '?':
00098       __argp_state_help (state, state->out_stream, ARGP_HELP_STD_HELP);
00099       break;
00100     case OPT_USAGE:
00101       __argp_state_help (state, state->out_stream,
00102                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_OK);
00103       break;
00104 
00105     case OPT_PROGNAME:          /* Set the program name.  */
00106 #if defined _LIBC || HAVE_DECL_PROGRAM_INVOCATION_NAME
00107       program_invocation_name = arg;
00108 #endif
00109       /* [Note that some systems only have PROGRAM_INVOCATION_SHORT_NAME (aka
00110          __PROGNAME), in which case, PROGRAM_INVOCATION_NAME is just defined
00111          to be that, so we have to be a bit careful here.]  */
00112 
00113       /* Update what we use for messages.  */
00114       state->name = strrchr (arg, '/');
00115       if (state->name)
00116         state->name++;
00117       else
00118         state->name = arg;
00119 
00120 #if defined _LIBC || HAVE_DECL_PROGRAM_INVOCATION_SHORT_NAME
00121       program_invocation_short_name = state->name;
00122 #endif
00123 
00124       if ((state->flags & (ARGP_PARSE_ARGV0 | ARGP_NO_ERRS))
00125           == ARGP_PARSE_ARGV0)
00126         /* Update what getopt uses too.  */
00127         state->argv[0] = arg;
00128 
00129       break;
00130 
00131     case OPT_HANG:
00132       _argp_hang = atoi (arg ? arg : "3600");
00133       while (_argp_hang-- > 0)
00134         ;// sleep (1);
00135       break;
00136 
00137     default:
00138       return EBADKEY;
00139     }
00140   return 0;
00141 }
00142 
00143 static const struct argp argp_default_argp =
00144   {argp_default_options, &argp_default_parser, NULL, NULL, NULL, NULL, "libc"};
00145 
00146 
00147 static const struct argp_option argp_version_options[] =
00148 {
00149   {"version",     'V',          0, 0,  N_("Print program version"), -1},
00150   {NULL, 0, 0, 0, NULL, 0}
00151 };
00152 
00153 static error_t
00154 argp_version_parser (int key, char *arg, struct argp_state *state)
00155 {
00156   switch (key)
00157     {
00158     case 'V':
00159       if (argp_program_version_hook)
00160         (*argp_program_version_hook) (state->out_stream, state);
00161       else if (argp_program_version)
00162         fprintf (state->out_stream, "%s\n", argp_program_version);
00163       else
00164         __argp_error (state, dgettext (state->root_argp->argp_domain,
00165                                        "(PROGRAM ERROR) No version known!?"));
00166       if (! (state->flags & ARGP_NO_EXIT))
00167         exit (0);
00168       break;
00169     default:
00170       return EBADKEY;
00171     }
00172   return 0;
00173 }
00174 
00175 static const struct argp argp_version_argp =
00176   {argp_version_options, &argp_version_parser, NULL, NULL, NULL, NULL, "libc"};
00177 
00178 /* Returns the offset into the getopt long options array LONG_OPTIONS of a
00179    long option with called NAME, or -1 if none is found.  Passing NULL as
00180    NAME will return the number of options.  */
00181 static int
00182 find_long_option (struct option *long_options, const char *name)
00183 {
00184   struct option *l = long_options;
00185   while (l->name != NULL)
00186     if (name != NULL && strcmp (l->name, name) == 0)
00187       return l - long_options;
00188     else
00189       l++;
00190   if (name == NULL)
00191     return l - long_options;
00192   else
00193     return -1;
00194 }
00195 
00196 
00197 /* The state of a `group' during parsing.  Each group corresponds to a
00198    particular argp structure from the tree of such descending from the top
00199    level argp passed to argp_parse.  */
00200 struct group
00201 {
00202   /* This group's parsing function.  */
00203   argp_parser_t parser;
00204 
00205   /* Which argp this group is from.  */
00206   const struct argp *argp;
00207 
00208   /* Points to the point in SHORT_OPTS corresponding to the end of the short
00209      options for this group.  We use it to determine from which group a
00210      particular short options is from.  */
00211   char *short_end;
00212 
00213   /* The number of non-option args sucessfully handled by this parser.  */
00214   unsigned args_processed;
00215 
00216   /* This group's parser's parent's group.  */
00217   struct group *parent;
00218   unsigned parent_index;        /* And the our position in the parent.   */
00219 
00220   /* These fields are swapped into and out of the state structure when
00221      calling this group's parser.  */
00222   void *input, **child_inputs;
00223   void *hook;
00224 };
00225 
00226 /* Call GROUP's parser with KEY and ARG, swapping any group-specific info
00227    from STATE before calling, and back into state afterwards.  If GROUP has
00228    no parser, EBADKEY is returned.  */
00229 static error_t
00230 group_parse (struct group *group, struct argp_state *state, int key, char *arg)
00231 {
00232   if (group->parser)
00233     {
00234       error_t err;
00235       state->hook = group->hook;
00236       state->input = group->input;
00237       state->child_inputs = group->child_inputs;
00238       state->arg_num = group->args_processed;
00239       err = (*group->parser)(key, arg, state);
00240       group->hook = state->hook;
00241       return err;
00242     }
00243   else
00244     return EBADKEY;
00245 }
00246 
00247 struct parser
00248 {
00249   const struct argp *argp;
00250 
00251   /* SHORT_OPTS is the getopt short options string for the union of all the
00252      groups of options.  */
00253   char *short_opts;
00254   /* LONG_OPTS is the array of getop long option structures for the union of
00255      all the groups of options.  */
00256   struct option *long_opts;
00257   /* OPT_DATA is the getopt data used for the re-entrant getopt.  */
00258   struct _getopt_data opt_data;
00259 
00260   /* States of the various parsing groups.  */
00261   struct group *groups;
00262   /* The end of the GROUPS array.  */
00263   struct group *egroup;
00264   /* An vector containing storage for the CHILD_INPUTS field in all groups.  */
00265   void **child_inputs;
00266 
00267   /* True if we think using getopt is still useful; if false, then
00268      remaining arguments are just passed verbatim with ARGP_KEY_ARG.  This is
00269      cleared whenever getopt returns KEY_END, but may be set again if the user
00270      moves the next argument pointer backwards.  */
00271   int try_getopt;
00272 
00273   /* State block supplied to parsing routines.  */
00274   struct argp_state state;
00275 
00276   /* Memory used by this parser.  */
00277   void *storage;
00278 };
00279 
00280 /* The next usable entries in the various parser tables being filled in by
00281    convert_options.  */
00282 struct parser_convert_state
00283 {
00284   struct parser *parser;
00285   char *short_end;
00286   struct option *long_end;
00287   void **child_inputs_end;
00288 };
00289 
00290 /* Converts all options in ARGP (which is put in GROUP) and ancestors
00291    into getopt options stored in SHORT_OPTS and LONG_OPTS; SHORT_END and
00292    CVT->LONG_END are the points at which new options are added.  Returns the
00293    next unused group entry.  CVT holds state used during the conversion.  */
00294 static struct group *
00295 convert_options (const struct argp *argp,
00296                  struct group *parent, unsigned parent_index,
00297                  struct group *group, struct parser_convert_state *cvt)
00298 {
00299   /* REAL is the most recent non-alias value of OPT.  */
00300   const struct argp_option *real = argp->options;
00301   const struct argp_child *children = argp->children;
00302 
00303   if (real || argp->parser)
00304     {
00305       const struct argp_option *opt;
00306 
00307       if (real)
00308         for (opt = real; !__option_is_end (opt); opt++)
00309           {
00310             if (! (opt->flags & OPTION_ALIAS))
00311               /* OPT isn't an alias, so we can use values from it.  */
00312               real = opt;
00313 
00314             if (! (real->flags & OPTION_DOC))
00315               /* A real option (not just documentation).  */
00316               {
00317                 if (__option_is_short (opt))
00318                   /* OPT can be used as a short option.  */
00319                   {
00320                     *cvt->short_end++ = opt->key;
00321                     if (real->arg)
00322                       {
00323                         *cvt->short_end++ = ':';
00324                         if (real->flags & OPTION_ARG_OPTIONAL)
00325                           *cvt->short_end++ = ':';
00326                       }
00327                     *cvt->short_end = '\0'; /* keep 0 terminated */
00328                   }
00329 
00330                 if (opt->name
00331                     && find_long_option (cvt->parser->long_opts, opt->name) < 0)
00332                   /* OPT can be used as a long option.  */
00333                   {
00334                     cvt->long_end->name = opt->name;
00335                     cvt->long_end->has_arg =
00336                       (real->arg
00337                        ? (real->flags & OPTION_ARG_OPTIONAL
00338                           ? optional_argument
00339                           : required_argument)
00340                        : no_argument);
00341                     cvt->long_end->flag = 0;
00342                     /* we add a disambiguating code to all the user's
00343                        values (which is removed before we actually call
00344                        the function to parse the value); this means that
00345                        the user loses use of the high 8 bits in all his
00346                        values (the sign of the lower bits is preserved
00347                        however)...  */
00348                     cvt->long_end->val =
00349                       ((opt->key | real->key) & USER_MASK)
00350                       + (((group - cvt->parser->groups) + 1) << USER_BITS);
00351 
00352                     /* Keep the LONG_OPTS list terminated.  */
00353                     (++cvt->long_end)->name = NULL;
00354                   }
00355               }
00356             }
00357 
00358       group->parser = argp->parser;
00359       group->argp = argp;
00360       group->short_end = cvt->short_end;
00361       group->args_processed = 0;
00362       group->parent = parent;
00363       group->parent_index = parent_index;
00364       group->input = 0;
00365       group->hook = 0;
00366       group->child_inputs = 0;
00367 
00368       if (children)
00369         /* Assign GROUP's CHILD_INPUTS field some space from
00370            CVT->child_inputs_end.*/
00371         {
00372           unsigned num_children = 0;
00373           while (children[num_children].argp)
00374             num_children++;
00375           group->child_inputs = cvt->child_inputs_end;
00376           cvt->child_inputs_end += num_children;
00377         }
00378 
00379       parent = group++;
00380     }
00381   else
00382     parent = 0;
00383 
00384   if (children)
00385     {
00386       unsigned index = 0;
00387       while (children->argp)
00388         group =
00389           convert_options (children++->argp, parent, index++, group, cvt);
00390     }
00391 
00392   return group;
00393 }
00394 
00395 /* Find the merged set of getopt options, with keys appropiately prefixed. */
00396 static void
00397 parser_convert (struct parser *parser, const struct argp *argp, int flags)
00398 {
00399   struct parser_convert_state cvt;
00400 
00401   cvt.parser = parser;
00402   cvt.short_end = parser->short_opts;
00403   cvt.long_end = parser->long_opts;
00404   cvt.child_inputs_end = parser->child_inputs;
00405 
00406   if (flags & ARGP_IN_ORDER)
00407     *cvt.short_end++ = '-';
00408   else if (flags & ARGP_NO_ARGS)
00409     *cvt.short_end++ = '+';
00410   *cvt.short_end = '\0';
00411 
00412   cvt.long_end->name = NULL;
00413 
00414   parser->argp = argp;
00415 
00416   if (argp)
00417     parser->egroup = convert_options (argp, 0, 0, parser->groups, &cvt);
00418   else
00419     parser->egroup = parser->groups; /* No parsers at all! */
00420 }
00421 
00422 /* Lengths of various parser fields which we will allocated.  */
00423 struct parser_sizes
00424 {
00425   size_t short_len;             /* Getopt short options string.  */
00426   size_t long_len;              /* Getopt long options vector.  */
00427   size_t num_groups;            /* Group structures we allocate.  */
00428   size_t num_child_inputs;      /* Child input slots.  */
00429 };
00430 
00431 /* For ARGP, increments the NUM_GROUPS field in SZS by the total number of
00432  argp structures descended from it, and the SHORT_LEN & LONG_LEN fields by
00433  the maximum lengths of the resulting merged getopt short options string and
00434  long-options array, respectively.  */
00435 static void
00436 calc_sizes (const struct argp *argp,  struct parser_sizes *szs)
00437 {
00438   const struct argp_child *child = argp->children;
00439   const struct argp_option *opt = argp->options;
00440 
00441   if (opt || argp->parser)
00442     {
00443       szs->num_groups++;
00444       if (opt)
00445         {
00446           int num_opts = 0;
00447           while (!__option_is_end (opt++))
00448             num_opts++;
00449           szs->short_len += num_opts * 3; /* opt + up to 2 `:'s */
00450           szs->long_len += num_opts;
00451         }
00452     }
00453 
00454   if (child)
00455     while (child->argp)
00456       {
00457         calc_sizes ((child++)->argp, szs);
00458         szs->num_child_inputs++;
00459       }
00460 }
00461 
00462 /* Initializes PARSER to parse ARGP in a manner described by FLAGS.  */
00463 static error_t
00464 parser_init (struct parser *parser, const struct argp *argp,
00465              int argc, char **argv, int flags, void *input)
00466 {
00467   error_t err = 0;
00468   struct group *group;
00469   struct parser_sizes szs;
00470   struct _getopt_data opt_data = _GETOPT_DATA_INITIALIZER;
00471   char *storage;
00472   size_t glen, gsum;
00473   size_t clen, csum;
00474   size_t llen, lsum;
00475   size_t slen, ssum;
00476 
00477   szs.short_len = (flags & ARGP_NO_ARGS) ? 0 : 1;
00478   szs.long_len = 0;
00479   szs.num_groups = 0;
00480   szs.num_child_inputs = 0;
00481 
00482   if (argp)
00483     calc_sizes (argp, &szs);
00484 
00485   /* Lengths of the various bits of storage used by PARSER.  */
00486   glen = (szs.num_groups + 1) * sizeof (struct group);
00487   clen = szs.num_child_inputs * sizeof (void *);
00488   llen = (szs.long_len + 1) * sizeof (struct option);
00489   slen = szs.short_len + 1;
00490 
00491   /* Sums of previous lengths, properly aligned.  There's no need to
00492      align gsum, since struct group is aligned at least as strictly as
00493      void * (since it contains a void * member).  And there's no need
00494      to align lsum, since struct option is aligned at least as
00495      strictly as char.  */
00496   gsum = glen;
00497   csum = alignto (gsum + clen, alignof (struct option));
00498   lsum = csum + llen;
00499   ssum = lsum + slen;
00500 
00501   parser->storage = malloc (ssum);
00502   if (! parser->storage)
00503     return ENOMEM;
00504 
00505   storage = parser->storage;
00506   parser->groups = parser->storage;
00507   parser->child_inputs = (void **) (storage + gsum);
00508   parser->long_opts = (struct option *) (storage + csum);
00509   parser->short_opts = storage + lsum;
00510   parser->opt_data = opt_data;
00511 
00512   memset (parser->child_inputs, 0, clen);
00513   parser_convert (parser, argp, flags);
00514 
00515   memset (&parser->state, 0, sizeof (struct argp_state));
00516   parser->state.root_argp = parser->argp;
00517   parser->state.argc = argc;
00518   parser->state.argv = argv;
00519   parser->state.flags = flags;
00520   parser->state.err_stream = stderr;
00521   parser->state.out_stream = stdout;
00522   parser->state.next = 0;       /* Tell getopt to initialize.  */
00523   parser->state.pstate = parser;
00524 
00525   parser->try_getopt = 1;
00526 
00527   /* Call each parser for the first time, giving it a chance to propagate
00528      values to child parsers.  */
00529   if (parser->groups < parser->egroup)
00530     parser->groups->input = input;
00531   for (group = parser->groups;
00532        group < parser->egroup && (!err || err == EBADKEY);
00533        group++)
00534     {
00535       if (group->parent)
00536         /* If a child parser, get the initial input value from the parent. */
00537         group->input = group->parent->child_inputs[group->parent_index];
00538 
00539       if (!group->parser
00540           && group->argp->children && group->argp->children->argp)
00541         /* For the special case where no parsing function is supplied for an
00542            argp, propagate its input to its first child, if any (this just
00543            makes very simple wrapper argps more convenient).  */
00544         group->child_inputs[0] = group->input;
00545 
00546       err = group_parse (group, &parser->state, ARGP_KEY_INIT, 0);
00547     }
00548   if (err == EBADKEY)
00549     err = 0;                    /* Some parser didn't understand.  */
00550 
00551   if (err)
00552     return err;
00553 
00554   if (parser->state.flags & ARGP_NO_ERRS)
00555     {
00556       parser->opt_data.opterr = 0;
00557       if (parser->state.flags & ARGP_PARSE_ARGV0)
00558         /* getopt always skips ARGV[0], so we have to fake it out.  As long
00559            as OPTERR is 0, then it shouldn't actually try to access it.  */
00560         parser->state.argv--, parser->state.argc++;
00561     }
00562   else
00563     parser->opt_data.opterr = 1;        /* Print error messages.  */
00564 
00565   if (parser->state.argv == argv && argv[0])
00566     /* There's an argv[0]; use it for messages.  */
00567     {
00568       char *short_name = strrchr (argv[0], '/');
00569       parser->state.name = short_name ? short_name + 1 : argv[0];
00570     }
00571   else
00572     parser->state.name = __argp_short_program_name ();
00573 
00574   return 0;
00575 }
00576 
00577 /* Free any storage consumed by PARSER (but not PARSER itself).  */
00578 static error_t
00579 parser_finalize (struct parser *parser,
00580                  error_t err, int arg_ebadkey, int *end_index)
00581 {
00582   struct group *group;
00583 
00584   if (err == EBADKEY && arg_ebadkey)
00585     /* Suppress errors generated by unparsed arguments.  */
00586     err = 0;
00587 
00588   if (! err)
00589     {
00590       if (parser->state.next == parser->state.argc)
00591         /* We successfully parsed all arguments!  Call all the parsers again,
00592            just a few more times... */
00593         {
00594           for (group = parser->groups;
00595                group < parser->egroup && (!err || err==EBADKEY);
00596                group++)
00597             if (group->args_processed == 0)
00598               err = group_parse (group, &parser->state, ARGP_KEY_NO_ARGS, 0);
00599           for (group = parser->egroup - 1;
00600                group >= parser->groups && (!err || err==EBADKEY);
00601                group--)
00602             err = group_parse (group, &parser->state, ARGP_KEY_END, 0);
00603 
00604           if (err == EBADKEY)
00605             err = 0;            /* Some parser didn't understand.  */
00606 
00607           /* Tell the user that all arguments are parsed.  */
00608           if (end_index)
00609             *end_index = parser->state.next;
00610         }
00611       else if (end_index)
00612         /* Return any remaining arguments to the user.  */
00613         *end_index = parser->state.next;
00614       else
00615         /* No way to return the remaining arguments, they must be bogus. */
00616         {
00617           if (!(parser->state.flags & ARGP_NO_ERRS)
00618               && parser->state.err_stream)
00619             fprintf (parser->state.err_stream,
00620                      dgettext (parser->argp->argp_domain,
00621                                "%s: Too many arguments\n"),
00622                      parser->state.name);
00623           err = EBADKEY;
00624         }
00625     }
00626 
00627   /* Okay, we're all done, with either an error or success; call the parsers
00628      to indicate which one.  */
00629 
00630   if (err)
00631     {
00632       /* Maybe print an error message.  */
00633       if (err == EBADKEY)
00634         /* An appropriate message describing what the error was should have
00635            been printed earlier.  */
00636         __argp_state_help (&parser->state, parser->state.err_stream,
00637                            ARGP_HELP_STD_ERR);
00638 
00639       /* Since we didn't exit, give each parser an error indication.  */
00640       for (group = parser->groups; group < parser->egroup; group++)
00641         group_parse (group, &parser->state, ARGP_KEY_ERROR, 0);
00642     }
00643   else
00644     /* Notify parsers of success, and propagate back values from parsers.  */
00645     {
00646       /* We pass over the groups in reverse order so that child groups are
00647          given a chance to do there processing before passing back a value to
00648          the parent.  */
00649       for (group = parser->egroup - 1
00650            ; group >= parser->groups && (!err || err == EBADKEY)
00651            ; group--)
00652         err = group_parse (group, &parser->state, ARGP_KEY_SUCCESS, 0);
00653       if (err == EBADKEY)
00654         err = 0;                /* Some parser didn't understand.  */
00655     }
00656 
00657   /* Call parsers once more, to do any final cleanup.  Errors are ignored.  */
00658   for (group = parser->egroup - 1; group >= parser->groups; group--)
00659     group_parse (group, &parser->state, ARGP_KEY_FINI, 0);
00660 
00661   if (err == EBADKEY)
00662     err = EINVAL;
00663 
00664   free (parser->storage);
00665 
00666   return err;
00667 }
00668 
00669 /* Call the user parsers to parse the non-option argument VAL, at the current
00670    position, returning any error.  The state NEXT pointer is assumed to have
00671    been adjusted (by getopt) to point after this argument; this function will
00672    adjust it correctly to reflect however many args actually end up being
00673    consumed.  */
00674 static error_t
00675 parser_parse_arg (struct parser *parser, char *val)
00676 {
00677   /* Save the starting value of NEXT, first adjusting it so that the arg
00678      we're parsing is again the front of the arg vector.  */
00679   int index = --parser->state.next;
00680   error_t err = EBADKEY;
00681   struct group *group;
00682   int key = 0;                  /* Which of ARGP_KEY_ARG[S] we used.  */
00683 
00684   /* Try to parse the argument in each parser.  */
00685   for (group = parser->groups
00686        ; group < parser->egroup && err == EBADKEY
00687        ; group++)
00688     {
00689       parser->state.next++;     /* For ARGP_KEY_ARG, consume the arg.  */
00690       key = ARGP_KEY_ARG;
00691       err = group_parse (group, &parser->state, key, val);
00692 
00693       if (err == EBADKEY)
00694         /* This parser doesn't like ARGP_KEY_ARG; try ARGP_KEY_ARGS instead. */
00695         {
00696           parser->state.next--; /* For ARGP_KEY_ARGS, put back the arg.  */
00697           key = ARGP_KEY_ARGS;
00698           err = group_parse (group, &parser->state, key, 0);
00699         }
00700     }
00701 
00702   if (! err)
00703     {
00704       if (key == ARGP_KEY_ARGS)
00705         /* The default for ARGP_KEY_ARGS is to assume that if NEXT isn't
00706            changed by the user, *all* arguments should be considered
00707            consumed.  */
00708         parser->state.next = parser->state.argc;
00709 
00710       if (parser->state.next > index)
00711         /* Remember that we successfully processed a non-option
00712            argument -- but only if the user hasn't gotten tricky and set
00713            the clock back.  */
00714         (--group)->args_processed += (parser->state.next - index);
00715       else
00716         /* The user wants to reparse some args, give getopt another try.  */
00717         parser->try_getopt = 1;
00718     }
00719 
00720   return err;
00721 }
00722 
00723 /* Call the user parsers to parse the option OPT, with argument VAL, at the
00724    current position, returning any error.  */
00725 static error_t
00726 parser_parse_opt (struct parser *parser, int opt, char *val)
00727 {
00728   /* The group key encoded in the high bits; 0 for short opts or
00729      group_number + 1 for long opts.  */
00730   int group_key = opt >> USER_BITS;
00731   error_t err = EBADKEY;
00732 
00733   if (group_key == 0)
00734     /* A short option.  By comparing OPT's position in SHORT_OPTS to the
00735        various starting positions in each group's SHORT_END field, we can
00736        determine which group OPT came from.  */
00737     {
00738       struct group *group;
00739       char *short_index = strchr (parser->short_opts, opt);
00740 
00741       if (short_index)
00742         for (group = parser->groups; group < parser->egroup; group++)
00743           if (group->short_end > short_index)
00744             {
00745               err = group_parse (group, &parser->state, opt,
00746                                  parser->opt_data.optarg);
00747               break;
00748             }
00749     }
00750   else
00751     /* A long option.  We use shifts instead of masking for extracting
00752        the user value in order to preserve the sign.  */
00753     err =
00754       group_parse (&parser->groups[group_key - 1], &parser->state,
00755                    (opt << GROUP_BITS) >> GROUP_BITS,
00756                    parser->opt_data.optarg);
00757 
00758   if (err == EBADKEY)
00759     /* At least currently, an option not recognized is an error in the
00760        parser, because we pre-compute which parser is supposed to deal
00761        with each option.  */
00762     {
00763       static const char bad_key_err[] =
00764         N_("(PROGRAM ERROR) Option should have been recognized!?");
00765       if (group_key == 0)
00766         __argp_error (&parser->state, "-%c: %s", opt,
00767                       dgettext (parser->argp->argp_domain, bad_key_err));
00768       else
00769         {
00770           struct option *long_opt = parser->long_opts;
00771           while (long_opt->val != opt && long_opt->name)
00772             long_opt++;
00773           __argp_error (&parser->state, "--%s: %s",
00774                         long_opt->name ? long_opt->name : "???",
00775                         dgettext (parser->argp->argp_domain, bad_key_err));
00776         }
00777     }
00778 
00779   return err;
00780 }
00781 
00782 /* Parse the next argument in PARSER (as indicated by PARSER->state.next).
00783    Any error from the parsers is returned, and *ARGP_EBADKEY indicates
00784    whether a value of EBADKEY is due to an unrecognized argument (which is
00785    generally not fatal).  */
00786 static error_t
00787 parser_parse_next (struct parser *parser, int *arg_ebadkey)
00788 {
00789   int opt;
00790   error_t err = 0;
00791 
00792   if (parser->state.quoted && parser->state.next < parser->state.quoted)
00793     /* The next argument pointer has been moved to before the quoted
00794        region, so pretend we never saw the quoting `--', and give getopt
00795        another chance.  If the user hasn't removed it, getopt will just
00796        process it again.  */
00797     parser->state.quoted = 0;
00798 
00799   if (parser->try_getopt && !parser->state.quoted)
00800     /* Give getopt a chance to parse this.  */
00801     {
00802       /* Put it back in OPTIND for getopt.  */
00803       parser->opt_data.optind = parser->state.next;
00804       /* Distinguish KEY_ERR from a real option.  */
00805       parser->opt_data.optopt = KEY_END;
00806       if (parser->state.flags & ARGP_LONG_ONLY)
00807         opt = _getopt_long_only_r (parser->state.argc, parser->state.argv,
00808                                    parser->short_opts, parser->long_opts, 0,
00809                                    &parser->opt_data);
00810       else
00811         opt = _getopt_long_r (parser->state.argc, parser->state.argv,
00812                               parser->short_opts, parser->long_opts, 0,
00813                               &parser->opt_data);
00814       /* And see what getopt did.  */
00815       parser->state.next = parser->opt_data.optind;
00816 
00817       if (opt == KEY_END)
00818         /* Getopt says there are no more options, so stop using
00819            getopt; we'll continue if necessary on our own.  */
00820         {
00821           parser->try_getopt = 0;
00822           if (parser->state.next > 1
00823               && strcmp (parser->state.argv[parser->state.next - 1], QUOTE)
00824                    == 0)
00825             /* Not only is this the end of the options, but it's a
00826                `quoted' region, which may have args that *look* like
00827                options, so we definitely shouldn't try to use getopt past
00828                here, whatever happens.  */
00829             parser->state.quoted = parser->state.next;
00830         }
00831       else if (opt == KEY_ERR && parser->opt_data.optopt != KEY_END)
00832         /* KEY_ERR can have the same value as a valid user short
00833            option, but in the case of a real error, getopt sets OPTOPT
00834            to the offending character, which can never be KEY_END.  */
00835         {
00836           *arg_ebadkey = 0;
00837           return EBADKEY;
00838         }
00839     }
00840   else
00841     opt = KEY_END;
00842 
00843   if (opt == KEY_END)
00844     {
00845       /* We're past what getopt considers the options.  */
00846       if (parser->state.next >= parser->state.argc
00847           || (parser->state.flags & ARGP_NO_ARGS))
00848         /* Indicate that we're done.  */
00849         {
00850           *arg_ebadkey = 1;
00851           return EBADKEY;
00852         }
00853       else
00854         /* A non-option arg; simulate what getopt might have done.  */
00855         {
00856           opt = KEY_ARG;
00857           parser->opt_data.optarg = parser->state.argv[parser->state.next++];
00858         }
00859     }
00860 
00861   if (opt == KEY_ARG)
00862     /* A non-option argument; try each parser in turn.  */
00863     err = parser_parse_arg (parser, parser->opt_data.optarg);
00864   else
00865     err = parser_parse_opt (parser, opt, parser->opt_data.optarg);
00866 
00867   if (err == EBADKEY)
00868     *arg_ebadkey = (opt == KEY_END || opt == KEY_ARG);
00869 
00870   return err;
00871 }
00872 
00873 /* Parse the options strings in ARGC & ARGV according to the argp in ARGP.
00874    FLAGS is one of the ARGP_ flags above.  If END_INDEX is non-NULL, the
00875    index in ARGV of the first unparsed option is returned in it.  If an
00876    unknown option is present, EINVAL is returned; if some parser routine
00877    returned a non-zero value, it is returned; otherwise 0 is returned.  */
00878 error_t
00879 __argp_parse (const struct argp *argp, int argc, char **argv, unsigned flags,
00880               int *end_index, void *input)
00881 {
00882   error_t err;
00883   struct parser parser;
00884 
00885   /* If true, then err == EBADKEY is a result of a non-option argument failing
00886      to be parsed (which in some cases isn't actually an error).  */
00887   int arg_ebadkey = 0;
00888 
00889   if (! (flags & ARGP_NO_HELP))
00890     /* Add our own options.  */
00891     {
00892       struct argp_child *child = alloca (4 * sizeof (struct argp_child));
00893       struct argp *top_argp = alloca (sizeof (struct argp));
00894 
00895       /* TOP_ARGP has no options, it just serves to group the user & default
00896          argps.  */
00897       memset (top_argp, 0, sizeof (*top_argp));
00898       top_argp->children = child;
00899 
00900       memset (child, 0, 4 * sizeof (struct argp_child));
00901 
00902       if (argp)
00903         (child++)->argp = argp;
00904       (child++)->argp = &argp_default_argp;
00905       if (argp_program_version || argp_program_version_hook)
00906         (child++)->argp = &argp_version_argp;
00907       child->argp = 0;
00908 
00909       argp = top_argp;
00910     }
00911 
00912   /* Construct a parser for these arguments.  */
00913   err = parser_init (&parser, argp, argc, argv, flags, input);
00914 
00915   if (! err)
00916     /* Parse! */
00917     {
00918       while (! err)
00919         err = parser_parse_next (&parser, &arg_ebadkey);
00920       err = parser_finalize (&parser, err, arg_ebadkey, end_index);
00921     }
00922 
00923   return err;
00924 }
00925 #ifdef weak_alias
00926 weak_alias (__argp_parse, argp_parse)
00927 #endif
00928 
00929 /* Return the input field for ARGP in the parser corresponding to STATE; used
00930    by the help routines.  */
00931 void *
00932 __argp_input (const struct argp *argp, const struct argp_state *state)
00933 {
00934   if (state)
00935     {
00936       struct group *group;
00937       struct parser *parser = state->pstate;
00938 
00939       for (group = parser->groups; group < parser->egroup; group++)
00940         if (group->argp == argp)
00941           return group->input;
00942     }
00943 
00944   return 0;
00945 }
00946 #ifdef weak_alias
00947 weak_alias (__argp_input, _argp_input)
00948 #endif

Generated on Thu Jan 24 16:50:54 2008 for WvStreams by  doxygen 1.5.4