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

Generated on Mon Feb 5 10:54:27 2007 for WvStreams by  doxygen 1.5.1