WvStreams
argp-parse.c
1 /* Hierarchial argument parsing
2  Copyright (C) 1995, 96, 97, 98, 99, 2000,2003 Free Software Foundation, Inc.
3  This file is part of the GNU C Library.
4  Written by Miles Bader <miles@gnu.ai.mit.edu>.
5 
6  The GNU C Library is free software; you can redistribute it and/or
7  modify it under the terms of the GNU Library General Public License as
8  published by the Free Software Foundation; either version 2 of the
9  License, or (at your option) any later version.
10 
11  The GNU C Library is distributed in the hope that it will be useful,
12  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  Library General Public License for more details.
15 
16  You should have received a copy of the GNU Library General Public
17  License along with the GNU C Library; see the file COPYING.LIB. If not,
18  write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  Boston, MA 02111-1307, USA. */
20 
21 #ifndef _GNU_SOURCE
22 # define _GNU_SOURCE 1
23 #endif
24 
25 #ifdef HAVE_CONFIG_H
26 #include <config.h>
27 #endif
28 
29 /* AIX requires this to be the first thing in the file. */
30 #ifndef __GNUC__
31 # if HAVE_ALLOCA_H
32 # include <alloca.h>
33 # else
34 # ifdef _AIX
35  #pragma alloca
36 # else
37 # ifndef alloca /* predefined by HP cc +Olibcalls */
38 char *alloca ();
39 # endif
40 # endif
41 # endif
42 #endif
43 
44 #include <stdlib.h>
45 #include <string.h>
46 #include <unistd.h>
47 #include <limits.h>
48 #include <assert.h>
49 #ifdef _WIN32
50 #include <malloc.h>
51 #endif
52 
53 #ifndef _
54 /* This is for other GNU distributions with internationalized messages.
55  When compiling libc, the _ macro is predefined. */
56 # if defined HAVE_LIBINTL_H || defined _LIBC
57 # include <libintl.h>
58 # ifdef _LIBC
59 # undef dgettext
60 # define dgettext(domain, msgid) __dcgettext (domain, msgid, LC_MESSAGES)
61 # endif
62 # else
63 # define dgettext(domain, msgid) (msgid)
64 # define gettext(msgid) (msgid)
65 # endif
66 #endif
67 #ifndef N_
68 # define N_(msgid) (msgid)
69 #endif
70 
71 #if _LIBC - 0
72 #include <bits/libc-lock.h>
73 #else
74 #ifdef HAVE_CTHREADS_H
75 #include <cthreads.h>
76 #endif
77 #endif /* _LIBC */
78 
79 #include "argp.h"
80 #include "argp-namefrob.h"
81 
82 
83 /* The meta-argument used to prevent any further arguments being interpreted
84  as options. */
85 #define QUOTE "--"
86 
87 /* EZ alias for ARGP_ERR_UNKNOWN. */
88 #define EBADKEY ARGP_ERR_UNKNOWN
89 
90 
91 /* Default options. */
92 
93 /* When argp is given the --HANG switch, _ARGP_HANG is set and argp will sleep
94  for one second intervals, decrementing _ARGP_HANG until it's zero. Thus
95  you can force the program to continue by attaching a debugger and setting
96  it to 0 yourself. */
97 volatile int _argp_hang;
98 
99 #define OPT_PROGNAME -2
100 #define OPT_USAGE -3
101 #define OPT_HANG -4
102 
103 static const struct argp_option argp_default_options[] =
104 {
105  {"help", '?', 0, 0, N_("Give this help list"), -1},
106  {"usage", OPT_USAGE, 0, 0, N_("Give a short usage message"), 0 },
107  {"program-name",OPT_PROGNAME,"NAME", OPTION_HIDDEN,
108  N_("Set the program name"), 0},
109  {"HANG", OPT_HANG, "SECS", OPTION_ARG_OPTIONAL | OPTION_HIDDEN,
110  N_("Hang for SECS seconds (default 3600)"), 0 },
111  {0, 0, 0, 0, 0, 0}
112 };
113 
114 static error_t
115 argp_default_parser (int key, char *arg, struct argp_state *state)
116 {
117  switch (key)
118  {
119  case '?':
120  __argp_state_help (state, state->out_stream, ARGP_HELP_STD_HELP);
121  break;
122  case OPT_USAGE:
123  __argp_state_help (state, state->out_stream,
124  ARGP_HELP_USAGE | ARGP_HELP_EXIT_OK);
125  break;
126 
127  case OPT_PROGNAME: /* Set the program name. */
128 #if HAVE_DECL_PROGRAM_INVOCATION_NAME
129  program_invocation_name = arg;
130 #endif
131  /* [Note that some systems only have PROGRAM_INVOCATION_SHORT_NAME (aka
132  __PROGNAME), in which case, PROGRAM_INVOCATION_NAME is just defined
133  to be that, so we have to be a bit careful here.] */
134 
135  /* Update what we use for messages. */
136 
137  state->name = __argp_basename(arg);
138 
139 #if HAVE_DECL_PROGRAM_INVOCATION_SHORT_NAME
140  program_invocation_short_name = state->name;
141 #endif
142 
143  if ((state->flags & (ARGP_PARSE_ARGV0 | ARGP_NO_ERRS))
144  == ARGP_PARSE_ARGV0)
145  /* Update what getopt uses too. */
146  state->argv[0] = arg;
147 
148  break;
149 
150  case OPT_HANG:
151  _argp_hang = atoi (arg ? arg : "3600");
152  fprintf(state->err_stream, "%s: pid = %ld\n",
153  state->name, (long) getpid());
154  while (_argp_hang-- > 0)
155  __sleep(1);
156  break;
157 
158  default:
159  return EBADKEY;
160  }
161  return 0;
162 }
163 
164 static const struct argp argp_default_argp =
165  {argp_default_options, &argp_default_parser, NULL, NULL, NULL, NULL, "libc"};
166 
167 
168 static const struct argp_option argp_version_options[] =
169 {
170  {"version", 'V', 0, 0, N_("Print program version"), -1},
171  {0, 0, 0, 0, 0, 0 }
172 };
173 
174 static error_t
175 argp_version_parser (int key, char *arg UNUSED, struct argp_state *state)
176 {
177  switch (key)
178  {
179  case 'V':
180  if (argp_program_version_hook)
181  (*argp_program_version_hook) (state->out_stream, state);
182  else if (argp_program_version)
183  fprintf (state->out_stream, "%s\n", argp_program_version);
184  else
185  __argp_error (state, dgettext (state->root_argp->argp_domain,
186  "(PROGRAM ERROR) No version known!?"));
187  if (! (state->flags & ARGP_NO_EXIT))
188  exit (0);
189  break;
190  default:
191  return EBADKEY;
192  }
193  return 0;
194 }
195 
196 static const struct argp argp_version_argp =
197  {argp_version_options, &argp_version_parser, NULL, NULL, NULL, NULL, "libc"};
198 
199 
200 
201 /* The state of a `group' during parsing. Each group corresponds to a
202  particular argp structure from the tree of such descending from the top
203  level argp passed to argp_parse. */
204 struct group
205 {
206  /* This group's parsing function. */
207  argp_parser_t parser;
208 
209  /* Which argp this group is from. */
210  const struct argp *argp;
211 
212  /* The number of non-option args sucessfully handled by this parser. */
213  unsigned args_processed;
214 
215  /* This group's parser's parent's group. */
216  struct group *parent;
217  unsigned parent_index; /* And the our position in the parent. */
218 
219  /* These fields are swapped into and out of the state structure when
220  calling this group's parser. */
221  void *input, **child_inputs;
222  void *hook;
223 };
224 
225 /* Call GROUP's parser with KEY and ARG, swapping any group-specific info
226  from STATE before calling, and back into state afterwards. If GROUP has
227  no parser, EBADKEY is returned. */
228 static error_t
229 group_parse (struct group *group, struct argp_state *state, int key, char *arg)
230 {
231  if (group->parser)
232  {
233  error_t err;
234  state->hook = group->hook;
235  state->input = group->input;
236  state->child_inputs = group->child_inputs;
237  state->arg_num = group->args_processed;
238  err = (*group->parser)(key, arg, state);
239  group->hook = state->hook;
240  return err;
241  }
242  else
243  return EBADKEY;
244 }
245 
246 struct parser
247 {
248  const struct argp *argp;
249 
250  const char *posixly_correct;
251 
252  /* True if there are only no-option arguments left, which are just
253  passed verbatim with ARGP_KEY_ARG. This is set if we encounter a
254  quote, or the end of the proper options, but may be cleared again
255  if the user moves the next argument pointer backwards. */
256  int args_only;
257 
258  /* Describe how to deal with options that follow non-option ARGV-elements.
259 
260  If the caller did not specify anything, the default is
261  REQUIRE_ORDER if the environment variable POSIXLY_CORRECT is
262  defined, PERMUTE otherwise.
263 
264  REQUIRE_ORDER means don't recognize them as options; stop option
265  processing when the first non-option is seen. This is what Unix
266  does. This mode of operation is selected by either setting the
267  environment variable POSIXLY_CORRECT, or using `+' as the first
268  character of the list of option characters.
269 
270  PERMUTE is the default. We permute the contents of ARGV as we
271  scan, so that eventually all the non-options are at the end. This
272  allows options to be given in any order, even with programs that
273  were not written to expect this.
274 
275  RETURN_IN_ORDER is an option available to programs that were
276  written to expect options and other ARGV-elements in any order
277  and that care about the ordering of the two. We describe each
278  non-option ARGV-element as if it were the argument of an option
279  with character code 1. Using `-' as the first character of the
280  list of option characters selects this mode of operation.
281 
282  */
283  enum { REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER } ordering;
284 
285  /* A segment of non-option arguments that have been skipped for
286  later processing, after all options. `first_nonopt' is the index
287  in ARGV of the first of them; `last_nonopt' is the index after
288  the last of them.
289 
290  If quoted or args_only is non-zero, this segment should be empty. */
291 
292  /* FIXME: I'd prefer to use unsigned, but it's more consistent to
293  use the same type as for state.next. */
294  int first_nonopt;
295  int last_nonopt;
296 
297  /* String of all recognized short options. Needed for ARGP_LONG_ONLY. */
298  /* FIXME: Perhaps change to a pointer to a suitable bitmap instead? */
299  char *short_opts;
300 
301  /* For parsing combined short options. */
302  char *nextchar;
303 
304  /* States of the various parsing groups. */
305  struct group *groups;
306  /* The end of the GROUPS array. */
307  struct group *egroup;
308  /* An vector containing storage for the CHILD_INPUTS field in all groups. */
309  void **child_inputs;
310 
311  /* State block supplied to parsing routines. */
312  struct argp_state state;
313 
314  /* Memory used by this parser. */
315  void *storage;
316 };
317 
318 /* Search for a group defining a short option. */
319 static const struct argp_option *
320 find_short_option(struct parser *parser, int key, struct group **p)
321 {
322  struct group *group;
323 
324  assert(key >= 0);
325  assert(isascii(key));
326 
327  for (group = parser->groups; group < parser->egroup; group++)
328  {
329  const struct argp_option *opts;
330 
331  for (opts = group->argp->options; !__option_is_end(opts); opts++)
332  if (opts->key == key)
333  {
334  *p = group;
335  return opts;
336  }
337  }
338  return NULL;
339 }
340 
341 enum match_result { MATCH_EXACT, MATCH_PARTIAL, MATCH_NO };
342 
343 /* If defined, allow complete.el-like abbreviations of long options. */
344 #ifndef ARGP_COMPLETE
345 #define ARGP_COMPLETE 0
346 #endif
347 
348 /* Matches an encountern long-option argument ARG against an option NAME.
349  * ARG is terminated by NUL or '='. */
350 static enum match_result
351 match_option(const char *arg, const char *name)
352 {
353  unsigned i, j;
354  for (i = j = 0;; i++, j++)
355  {
356  switch(arg[i])
357  {
358  case '\0':
359  case '=':
360  return name[j] ? MATCH_PARTIAL : MATCH_EXACT;
361 #if ARGP_COMPLETE
362  case '-':
363  while (name[j] != '-')
364  if (!name[j++])
365  return MATCH_NO;
366  break;
367 #endif
368  default:
369  if (arg[i] != name[j])
370  return MATCH_NO;
371  }
372  }
373 }
374 
375 static const struct argp_option *
376 find_long_option(struct parser *parser,
377  const char *arg,
378  struct group **p)
379 {
380  struct group *group;
381 
382  /* Partial match found so far. */
383  struct group *matched_group = NULL;
384  const struct argp_option *matched_option = NULL;
385 
386  /* Number of partial matches. */
387  int num_partial = 0;
388 
389  for (group = parser->groups; group < parser->egroup; group++)
390  {
391  const struct argp_option *opts;
392 
393  for (opts = group->argp->options; !__option_is_end(opts); opts++)
394  {
395  if (!opts->name)
396  continue;
397  switch (match_option(arg, opts->name))
398  {
399  case MATCH_NO:
400  break;
401  case MATCH_PARTIAL:
402  num_partial++;
403 
404  matched_group = group;
405  matched_option = opts;
406 
407  break;
408  case MATCH_EXACT:
409  /* Exact match. */
410  *p = group;
411  return opts;
412  }
413  }
414  }
415  if (num_partial == 1)
416  {
417  *p = matched_group;
418  return matched_option;
419  }
420 
421  return NULL;
422 }
423 
424 
425 /* The next usable entries in the various parser tables being filled in by
426  convert_options. */
428 {
429  struct parser *parser;
430  char *short_end;
431  void **child_inputs_end;
432 };
433 
434 /* Initialize GROUP from ARGP. If CVT->SHORT_END is non-NULL, short
435  options are recorded in the short options string. Returns the next
436  unused group entry. CVT holds state used during the conversion. */
437 static struct group *
438 convert_options (const struct argp *argp,
439  struct group *parent, unsigned parent_index,
440  struct group *group, struct parser_convert_state *cvt)
441 {
442  const struct argp_option *opt = argp->options;
443  const struct argp_child *children = argp->children;
444 
445  if (opt || argp->parser)
446  {
447  /* This parser needs a group. */
448  if (cvt->short_end)
449  {
450  /* Record any short options. */
451  for ( ; !__option_is_end (opt); opt++)
452  if (__option_is_short(opt))
453  *cvt->short_end++ = opt->key;
454  }
455 
456  group->parser = argp->parser;
457  group->argp = argp;
458  group->args_processed = 0;
459  group->parent = parent;
460  group->parent_index = parent_index;
461  group->input = 0;
462  group->hook = 0;
463  group->child_inputs = 0;
464 
465  if (children)
466  /* Assign GROUP's CHILD_INPUTS field some space from
467  CVT->child_inputs_end.*/
468  {
469  unsigned num_children = 0;
470  while (children[num_children].argp)
471  num_children++;
472  group->child_inputs = cvt->child_inputs_end;
473  cvt->child_inputs_end += num_children;
474  }
475  parent = group++;
476  }
477  else
478  parent = 0;
479 
480  if (children)
481  {
482  unsigned index = 0;
483  while (children->argp)
484  group =
485  convert_options (children++->argp, parent, index++, group, cvt);
486  }
487 
488  return group;
489 }
490 /* Allocate and initialize the group structures, so that they are
491  ordered as if by traversing the corresponding argp parser tree in
492  pre-order. Also build the list of short options, if that is needed. */
493 static void
494 parser_convert (struct parser *parser, const struct argp *argp)
495 {
496  struct parser_convert_state cvt;
497 
498  cvt.parser = parser;
499  cvt.short_end = parser->short_opts;
500  cvt.child_inputs_end = parser->child_inputs;
501 
502  parser->argp = argp;
503 
504  if (argp)
505  parser->egroup = convert_options (argp, 0, 0, parser->groups, &cvt);
506  else
507  parser->egroup = parser->groups; /* No parsers at all! */
508 
509  if (parser->short_opts)
510  *cvt.short_end ='\0';
511 }
512 
513 /* Lengths of various parser fields which we will allocated. */
515 {
516  /* Needed only ARGP_LONG_ONLY */
517  size_t short_len; /* Number of short options. */
518 
519  size_t num_groups; /* Group structures we allocate. */
520  size_t num_child_inputs; /* Child input slots. */
521 };
522 
523 /* For ARGP, increments the NUM_GROUPS field in SZS by the total
524  number of argp structures descended from it, and the SHORT_LEN by
525  the total number of short options. */
526 static void
527 calc_sizes (const struct argp *argp, struct parser_sizes *szs)
528 {
529  const struct argp_child *child = argp->children;
530  const struct argp_option *opt = argp->options;
531 
532  if (opt || argp->parser)
533  {
534  /* This parser needs a group. */
535  szs->num_groups++;
536  if (opt)
537  {
538  while (__option_is_short (opt++))
539  szs->short_len++;
540  }
541  }
542 
543  if (child)
544  while (child->argp)
545  {
546  calc_sizes ((child++)->argp, szs);
547  szs->num_child_inputs++;
548  }
549 }
550 
551 /* Initializes PARSER to parse ARGP in a manner described by FLAGS. */
552 static error_t
553 parser_init (struct parser *parser, const struct argp *argp,
554  int argc, char **argv, int flags, void *input)
555 {
556  error_t err = 0;
557  struct group *group;
558  struct parser_sizes szs;
559 
560  parser->posixly_correct = getenv ("POSIXLY_CORRECT");
561 
562  if (flags & ARGP_IN_ORDER)
563  parser->ordering = RETURN_IN_ORDER;
564  else if (flags & ARGP_NO_ARGS)
565  parser->ordering = REQUIRE_ORDER;
566  else if (parser->posixly_correct)
567  parser->ordering = REQUIRE_ORDER;
568  else
569  parser->ordering = PERMUTE;
570 
571  szs.short_len = 0;
572  szs.num_groups = 0;
573  szs.num_child_inputs = 0;
574 
575  if (argp)
576  calc_sizes (argp, &szs);
577 
578  if (!(flags & ARGP_LONG_ONLY))
579  /* We have no use for the short option array. */
580  szs.short_len = 0;
581 
582  /* Lengths of the various bits of storage used by PARSER. */
583 #define GLEN (szs.num_groups + 1) * sizeof (struct group)
584 #define CLEN (szs.num_child_inputs * sizeof (void *))
585 #define SLEN (szs.short_len + 1)
586 #define STORAGE(offset) ((void *) (((char *) parser->storage) + (offset)))
587 
588  parser->storage = malloc (GLEN + CLEN + SLEN);
589  if (! parser->storage)
590  return ENOMEM;
591 
592  parser->groups = parser->storage;
593 
594  parser->child_inputs = STORAGE(GLEN);
595  memset (parser->child_inputs, 0, szs.num_child_inputs * sizeof (void *));
596 
597  if (flags & ARGP_LONG_ONLY)
598  parser->short_opts = STORAGE(GLEN + CLEN);
599  else
600  parser->short_opts = NULL;
601 
602  parser_convert (parser, argp);
603 
604  memset (&parser->state, 0, sizeof (struct argp_state));
605 
606  parser->state.root_argp = parser->argp;
607  parser->state.argc = argc;
608  parser->state.argv = argv;
609  parser->state.flags = flags;
610  parser->state.err_stream = stderr;
611  parser->state.out_stream = stdout;
612  parser->state.pstate = parser;
613 
614  parser->args_only = 0;
615  parser->nextchar = NULL;
616  parser->first_nonopt = parser->last_nonopt = 0;
617 
618  /* Call each parser for the first time, giving it a chance to propagate
619  values to child parsers. */
620  if (parser->groups < parser->egroup)
621  parser->groups->input = input;
622  for (group = parser->groups;
623  group < parser->egroup && (!err || err == EBADKEY);
624  group++)
625  {
626  if (group->parent)
627  /* If a child parser, get the initial input value from the parent. */
628  group->input = group->parent->child_inputs[group->parent_index];
629 
630  if (!group->parser
631  && group->argp->children && group->argp->children->argp)
632  /* For the special case where no parsing function is supplied for an
633  argp, propagate its input to its first child, if any (this just
634  makes very simple wrapper argps more convenient). */
635  group->child_inputs[0] = group->input;
636 
637  err = group_parse (group, &parser->state, ARGP_KEY_INIT, 0);
638  }
639  if (err == EBADKEY)
640  err = 0; /* Some parser didn't understand. */
641 
642  if (err)
643  return err;
644 
645  if (argv[0] && !(parser->state.flags & ARGP_PARSE_ARGV0))
646  /* There's an argv[0]; use it for messages. */
647  {
648  parser->state.name = __argp_basename(argv[0]);
649 
650  /* Don't parse it as an argument. */
651  parser->state.next = 1;
652  }
653  else
654  parser->state.name = __argp_short_program_name(NULL);
655 
656  return 0;
657 }
658 
659 /* Free any storage consumed by PARSER (but not PARSER itself). */
660 static error_t
661 parser_finalize (struct parser *parser,
662  error_t err, int arg_ebadkey, int *end_index)
663 {
664  struct group *group;
665 
666  if (err == EBADKEY && arg_ebadkey)
667  /* Suppress errors generated by unparsed arguments. */
668  err = 0;
669 
670  if (! err)
671  {
672  if (parser->state.next == parser->state.argc)
673  /* We successfully parsed all arguments! Call all the parsers again,
674  just a few more times... */
675  {
676  for (group = parser->groups;
677  group < parser->egroup && (!err || err==EBADKEY);
678  group++)
679  if (group->args_processed == 0)
680  err = group_parse (group, &parser->state, ARGP_KEY_NO_ARGS, 0);
681  for (group = parser->egroup - 1;
682  group >= parser->groups && (!err || err==EBADKEY);
683  group--)
684  err = group_parse (group, &parser->state, ARGP_KEY_END, 0);
685 
686  if (err == EBADKEY)
687  err = 0; /* Some parser didn't understand. */
688 
689  /* Tell the user that all arguments are parsed. */
690  if (end_index)
691  *end_index = parser->state.next;
692  }
693  else if (end_index)
694  /* Return any remaining arguments to the user. */
695  *end_index = parser->state.next;
696  else
697  /* No way to return the remaining arguments, they must be bogus. */
698  {
699  if (!(parser->state.flags & ARGP_NO_ERRS)
700  && parser->state.err_stream)
701  fprintf (parser->state.err_stream,
702  dgettext (parser->argp->argp_domain,
703  "%s: Too many arguments\n"),
704  parser->state.name);
705  err = EBADKEY;
706  }
707  }
708 
709  /* Okay, we're all done, with either an error or success; call the parsers
710  to indicate which one. */
711 
712  if (err)
713  {
714  /* Maybe print an error message. */
715  if (err == EBADKEY)
716  /* An appropriate message describing what the error was should have
717  been printed earlier. */
718  __argp_state_help (&parser->state, parser->state.err_stream,
719  ARGP_HELP_STD_ERR);
720 
721  /* Since we didn't exit, give each parser an error indication. */
722  for (group = parser->groups; group < parser->egroup; group++)
723  group_parse (group, &parser->state, ARGP_KEY_ERROR, 0);
724  }
725  else
726  /* Notify parsers of success, and propagate back values from parsers. */
727  {
728  /* We pass over the groups in reverse order so that child groups are
729  given a chance to do there processing before passing back a value to
730  the parent. */
731  for (group = parser->egroup - 1
732  ; group >= parser->groups && (!err || err == EBADKEY)
733  ; group--)
734  err = group_parse (group, &parser->state, ARGP_KEY_SUCCESS, 0);
735  if (err == EBADKEY)
736  err = 0; /* Some parser didn't understand. */
737  }
738 
739  /* Call parsers once more, to do any final cleanup. Errors are ignored. */
740  for (group = parser->egroup - 1; group >= parser->groups; group--)
741  group_parse (group, &parser->state, ARGP_KEY_FINI, 0);
742 
743  if (err == EBADKEY)
744  err = EINVAL;
745 
746  free (parser->storage);
747 
748  return err;
749 }
750 
751 /* Call the user parsers to parse the non-option argument VAL, at the
752  current position, returning any error. The state NEXT pointer
753  should point to the argument; this function will adjust it
754  correctly to reflect however many args actually end up being
755  consumed. */
756 static error_t
757 parser_parse_arg (struct parser *parser, char *val)
758 {
759  /* Save the starting value of NEXT */
760  int index = parser->state.next;
761  error_t err = EBADKEY;
762  struct group *group;
763  int key = 0; /* Which of ARGP_KEY_ARG[S] we used. */
764 
765  /* Try to parse the argument in each parser. */
766  for (group = parser->groups
767  ; group < parser->egroup && err == EBADKEY
768  ; group++)
769  {
770  parser->state.next++; /* For ARGP_KEY_ARG, consume the arg. */
771  key = ARGP_KEY_ARG;
772  err = group_parse (group, &parser->state, key, val);
773 
774  if (err == EBADKEY)
775  /* This parser doesn't like ARGP_KEY_ARG; try ARGP_KEY_ARGS instead. */
776  {
777  parser->state.next--; /* For ARGP_KEY_ARGS, put back the arg. */
778  key = ARGP_KEY_ARGS;
779  err = group_parse (group, &parser->state, key, 0);
780  }
781  }
782 
783  if (! err)
784  {
785  if (key == ARGP_KEY_ARGS)
786  /* The default for ARGP_KEY_ARGS is to assume that if NEXT isn't
787  changed by the user, *all* arguments should be considered
788  consumed. */
789  parser->state.next = parser->state.argc;
790 
791  if (parser->state.next > index)
792  /* Remember that we successfully processed a non-option
793  argument -- but only if the user hasn't gotten tricky and set
794  the clock back. */
795  (--group)->args_processed += (parser->state.next - index);
796  else
797  /* The user wants to reparse some args, so try looking for options again. */
798  parser->args_only = 0;
799  }
800 
801  return err;
802 }
803 
804 /* Exchange two adjacent subsequences of ARGV.
805  One subsequence is elements [first_nonopt,last_nonopt)
806  which contains all the non-options that have been skipped so far.
807  The other is elements [last_nonopt,next), which contains all
808  the options processed since those non-options were skipped.
809 
810  `first_nonopt' and `last_nonopt' are relocated so that they describe
811  the new indices of the non-options in ARGV after they are moved. */
812 
813 static void
814 exchange (struct parser *parser)
815 {
816  int bottom = parser->first_nonopt;
817  int middle = parser->last_nonopt;
818  int top = parser->state.next;
819  char **argv = parser->state.argv;
820 
821  char *tem;
822 
823  /* Exchange the shorter segment with the far end of the longer segment.
824  That puts the shorter segment into the right place.
825  It leaves the longer segment in the right place overall,
826  but it consists of two parts that need to be swapped next. */
827 
828  while (top > middle && middle > bottom)
829  {
830  if (top - middle > middle - bottom)
831  {
832  /* Bottom segment is the short one. */
833  int len = middle - bottom;
834  register int i;
835 
836  /* Swap it with the top part of the top segment. */
837  for (i = 0; i < len; i++)
838  {
839  tem = argv[bottom + i];
840  argv[bottom + i] = argv[top - (middle - bottom) + i];
841  argv[top - (middle - bottom) + i] = tem;
842  }
843  /* Exclude the moved bottom segment from further swapping. */
844  top -= len;
845  }
846  else
847  {
848  /* Top segment is the short one. */
849  int len = top - middle;
850  register int i;
851 
852  /* Swap it with the bottom part of the bottom segment. */
853  for (i = 0; i < len; i++)
854  {
855  tem = argv[bottom + i];
856  argv[bottom + i] = argv[middle + i];
857  argv[middle + i] = tem;
858  }
859  /* Exclude the moved top segment from further swapping. */
860  bottom += len;
861  }
862  }
863 
864  /* Update records for the slots the non-options now occupy. */
865 
866  parser->first_nonopt += (parser->state.next - parser->last_nonopt);
867  parser->last_nonopt = parser->state.next;
868 }
869 
870 
871 
872 enum arg_type { ARG_ARG, ARG_SHORT_OPTION,
873  ARG_LONG_OPTION, ARG_LONG_ONLY_OPTION,
874  ARG_QUOTE };
875 
876 static enum arg_type
877 classify_arg(struct parser *parser, char *arg, char **opt)
878 {
879  if (arg[0] == '-')
880  /* Looks like an option... */
881  switch (arg[1])
882  {
883  case '\0':
884  /* "-" is not an option. */
885  return ARG_ARG;
886  case '-':
887  /* Long option, or quote. */
888  if (!arg[2])
889  return ARG_QUOTE;
890 
891  /* A long option. */
892  if (opt)
893  *opt = arg + 2;
894  return ARG_LONG_OPTION;
895 
896  default:
897  /* Short option. But if ARGP_LONG_ONLY, it can also be a long option. */
898 
899  if (opt)
900  *opt = arg + 1;
901 
902  if (parser->state.flags & ARGP_LONG_ONLY)
903  {
904  /* Rules from getopt.c:
905 
906  If long_only and the ARGV-element has the form "-f",
907  where f is a valid short option, don't consider it an
908  abbreviated form of a long option that starts with f.
909  Otherwise there would be no way to give the -f short
910  option.
911 
912  On the other hand, if there's a long option "fubar" and
913  the ARGV-element is "-fu", do consider that an
914  abbreviation of the long option, just like "--fu", and
915  not "-f" with arg "u".
916 
917  This distinction seems to be the most useful approach. */
918 
919  assert(parser->short_opts);
920 
921  if (arg[2] || !strchr(parser->short_opts, arg[1]))
922  return ARG_LONG_ONLY_OPTION;
923  }
924 
925  return ARG_SHORT_OPTION;
926  }
927 
928  else
929  return ARG_ARG;
930 }
931 
932 /* Parse the next argument in PARSER (as indicated by PARSER->state.next).
933  Any error from the parsers is returned, and *ARGP_EBADKEY indicates
934  whether a value of EBADKEY is due to an unrecognized argument (which is
935  generally not fatal). */
936 static error_t
937 parser_parse_next (struct parser *parser, int *arg_ebadkey)
938 {
939  if (parser->state.quoted && parser->state.next < parser->state.quoted)
940  /* The next argument pointer has been moved to before the quoted
941  region, so pretend we never saw the quoting `--', and start
942  looking for options again. If the `--' is still there we'll just
943  process it one more time. */
944  parser->state.quoted = parser->args_only = 0;
945 
946  /* Give FIRST_NONOPT & LAST_NONOPT rational values if NEXT has been
947  moved back by the user (who may also have changed the arguments). */
948  if (parser->last_nonopt > parser->state.next)
949  parser->last_nonopt = parser->state.next;
950  if (parser->first_nonopt > parser->state.next)
951  parser->first_nonopt = parser->state.next;
952 
953  if (parser->nextchar)
954  /* Deal with short options. */
955  {
956  struct group *group;
957  char c;
958  const struct argp_option *option;
959  char *value = NULL;;
960 
961  assert(!parser->args_only);
962 
963  c = *parser->nextchar++;
964 
965  option = find_short_option(parser, c, &group);
966  if (!option)
967  {
968  if (parser->posixly_correct)
969  /* 1003.2 specifies the format of this message. */
970  fprintf (parser->state.err_stream,
971  dgettext(parser->state.root_argp->argp_domain,
972  "%s: illegal option -- %c\n"),
973  parser->state.name, c);
974  else
975  fprintf (parser->state.err_stream,
976  dgettext(parser->state.root_argp->argp_domain,
977  "%s: invalid option -- %c\n"),
978  parser->state.name, c);
979 
980  *arg_ebadkey = 0;
981  return EBADKEY;
982  }
983 
984  if (!*parser->nextchar)
985  parser->nextchar = NULL;
986 
987  if (option->arg)
988  {
989  value = parser->nextchar;
990  parser->nextchar = NULL;
991 
992  if (!value
993  && !(option->flags & OPTION_ARG_OPTIONAL))
994  /* We need an mandatory argument. */
995  {
996  if (parser->state.next == parser->state.argc)
997  /* Missing argument */
998  {
999  /* 1003.2 specifies the format of this message. */
1000  fprintf (parser->state.err_stream,
1001  dgettext(parser->state.root_argp->argp_domain,
1002  "%s: option requires an argument -- %c\n"),
1003  parser->state.name, c);
1004 
1005  *arg_ebadkey = 0;
1006  return EBADKEY;
1007  }
1008  value = parser->state.argv[parser->state.next++];
1009  }
1010  }
1011  return group_parse(group, &parser->state,
1012  option->key, value);
1013  }
1014  else
1015  /* Advance to the next ARGV-element. */
1016  {
1017  if (parser->args_only)
1018  {
1019  *arg_ebadkey = 1;
1020  if (parser->state.next >= parser->state.argc)
1021  /* We're done. */
1022  return EBADKEY;
1023  else
1024  return parser_parse_arg(parser,
1025  parser->state.argv[parser->state.next]);
1026  }
1027 
1028  if (parser->state.next >= parser->state.argc)
1029  /* Almost done. If there are non-options that we skipped
1030  previously, we should process them now. */
1031  {
1032  *arg_ebadkey = 1;
1033  if (parser->first_nonopt != parser->last_nonopt)
1034  {
1035  exchange(parser);
1036 
1037  /* Start processing the arguments we skipped previously. */
1038  parser->state.next = parser->first_nonopt;
1039 
1040  parser->first_nonopt = parser->last_nonopt = 0;
1041 
1042  parser->args_only = 1;
1043  return 0;
1044  }
1045  else
1046  /* Indicate that we're really done. */
1047  return EBADKEY;
1048  }
1049  else
1050  /* Look for options. */
1051  {
1052  char *arg = parser->state.argv[parser->state.next];
1053 
1054  char *optstart;
1055  enum arg_type token = classify_arg(parser, arg, &optstart);
1056 
1057  switch (token)
1058  {
1059  case ARG_ARG:
1060  switch (parser->ordering)
1061  {
1062  case PERMUTE:
1063  if (parser->first_nonopt == parser->last_nonopt)
1064  /* Skipped sequence is empty; start a new one. */
1065  parser->first_nonopt = parser->last_nonopt = parser->state.next;
1066 
1067  else if (parser->last_nonopt != parser->state.next)
1068  /* We have a non-empty skipped sequence, and
1069  we're not at the end-point, so move it. */
1070  exchange(parser);
1071 
1072  assert(parser->last_nonopt == parser->state.next);
1073 
1074  /* Skip this argument for now. */
1075  parser->state.next++;
1076  parser->last_nonopt = parser->state.next;
1077 
1078  return 0;
1079 
1080  case REQUIRE_ORDER:
1081  /* Implicit quote before the first argument. */
1082  parser->args_only = 1;
1083  return 0;
1084 
1085  case RETURN_IN_ORDER:
1086  *arg_ebadkey = 1;
1087  return parser_parse_arg(parser, arg);
1088 
1089  default:
1090  abort();
1091  }
1092  case ARG_QUOTE:
1093  /* Skip it, then exchange with any previous non-options. */
1094  parser->state.next++;
1095  assert (parser->last_nonopt != parser->state.next);
1096 
1097  if (parser->first_nonopt != parser->last_nonopt)
1098  {
1099  exchange(parser);
1100 
1101  /* Start processing the skipped and the quoted
1102  arguments. */
1103 
1104  parser->state.quoted = parser->state.next = parser->first_nonopt;
1105 
1106  /* Also empty the skipped-list, to avoid confusion
1107  if the user resets the next pointer. */
1108  parser->first_nonopt = parser->last_nonopt = 0;
1109  }
1110  else
1111  parser->state.quoted = parser->state.next;
1112 
1113  parser->args_only = 1;
1114  return 0;
1115 
1116  case ARG_LONG_ONLY_OPTION:
1117  case ARG_LONG_OPTION:
1118  {
1119  struct group *group;
1120  const struct argp_option *option;
1121  char *value;
1122 
1123  parser->state.next++;
1124  option = find_long_option(parser, optstart, &group);
1125 
1126  if (!option)
1127  {
1128  /* NOTE: This includes any "=something" in the output. */
1129  fprintf (parser->state.err_stream,
1130  dgettext(parser->state.root_argp->argp_domain,
1131  "%s: unrecognized option `%s'\n"),
1132  parser->state.name, arg);
1133  *arg_ebadkey = 0;
1134  return EBADKEY;
1135  }
1136 
1137  value = strchr(optstart, '=');
1138  if (value)
1139  value++;
1140 
1141  if (value && !option->arg)
1142  /* Unexpected argument. */
1143  {
1144  if (token == ARG_LONG_OPTION)
1145  /* --option */
1146  fprintf (parser->state.err_stream,
1147  dgettext(parser->state.root_argp->argp_domain,
1148  "%s: option `--%s' doesn't allow an argument\n"),
1149  parser->state.name, option->name);
1150  else
1151  /* +option or -option */
1152  fprintf (parser->state.err_stream,
1153  dgettext(parser->state.root_argp->argp_domain,
1154  "%s: option `%c%s' doesn't allow an argument\n"),
1155  parser->state.name, arg[0], option->name);
1156 
1157  *arg_ebadkey = 0;
1158  return EBADKEY;
1159  }
1160 
1161  if (option->arg && !value
1162  && !(option->flags & OPTION_ARG_OPTIONAL))
1163  /* We need an mandatory argument. */
1164  {
1165  if (parser->state.next == parser->state.argc)
1166  /* Missing argument */
1167  {
1168  if (token == ARG_LONG_OPTION)
1169  /* --option */
1170  fprintf (parser->state.err_stream,
1171  dgettext(parser->state.root_argp->argp_domain,
1172  "%s: option `--%s' requires an argument\n"),
1173  parser->state.name, option->name);
1174  else
1175  /* +option or -option */
1176  fprintf (parser->state.err_stream,
1177  dgettext(parser->state.root_argp->argp_domain,
1178  "%s: option `%c%s' requires an argument\n"),
1179  parser->state.name, arg[0], option->name);
1180 
1181  *arg_ebadkey = 0;
1182  return EBADKEY;
1183  }
1184 
1185  value = parser->state.argv[parser->state.next++];
1186  }
1187  *arg_ebadkey = 0;
1188  return group_parse(group, &parser->state,
1189  option->key, value);
1190  }
1191  case ARG_SHORT_OPTION:
1192  parser->state.next++;
1193  parser->nextchar = optstart;
1194  return 0;
1195 
1196  default:
1197  abort();
1198  }
1199  }
1200  }
1201 }
1202 
1203 /* Parse the options strings in ARGC & ARGV according to the argp in ARGP.
1204  FLAGS is one of the ARGP_ flags above. If END_INDEX is non-NULL, the
1205  index in ARGV of the first unparsed option is returned in it. If an
1206  unknown option is present, EINVAL is returned; if some parser routine
1207  returned a non-zero value, it is returned; otherwise 0 is returned. */
1208 error_t
1209 __argp_parse (const struct argp *argp, int argc, char **argv, unsigned flags,
1210  int *end_index, void *input)
1211 {
1212  error_t err;
1213  struct parser parser;
1214 
1215  /* If true, then err == EBADKEY is a result of a non-option argument failing
1216  to be parsed (which in some cases isn't actually an error). */
1217  int arg_ebadkey = 0;
1218 
1219  if (! (flags & ARGP_NO_HELP))
1220  /* Add our own options. */
1221  {
1222  struct argp_child *child = alloca (4 * sizeof (struct argp_child));
1223  struct argp *top_argp = alloca (sizeof (struct argp));
1224 
1225  /* TOP_ARGP has no options, it just serves to group the user & default
1226  argps. */
1227  memset (top_argp, 0, sizeof (*top_argp));
1228  top_argp->children = child;
1229 
1230  memset (child, 0, 4 * sizeof (struct argp_child));
1231 
1232  if (argp)
1233  (child++)->argp = argp;
1234  (child++)->argp = &argp_default_argp;
1235  if (argp_program_version || argp_program_version_hook)
1236  (child++)->argp = &argp_version_argp;
1237  child->argp = 0;
1238 
1239  argp = top_argp;
1240  }
1241 
1242  /* Construct a parser for these arguments. */
1243  err = parser_init (&parser, argp, argc, argv, flags, input);
1244 
1245  if (! err)
1246  /* Parse! */
1247  {
1248  while (! err)
1249  err = parser_parse_next (&parser, &arg_ebadkey);
1250  err = parser_finalize (&parser, err, arg_ebadkey, end_index);
1251  }
1252 
1253  return err;
1254 }
1255 #ifdef weak_alias
1256 weak_alias (__argp_parse, argp_parse)
1257 #endif
1258 
1259 /* Return the input field for ARGP in the parser corresponding to STATE; used
1260  by the help routines. */
1261 void *
1262 __argp_input (const struct argp *argp, const struct argp_state *state)
1263 {
1264  if (state)
1265  {
1266  struct group *group;
1267  struct parser *parser = state->pstate;
1268 
1269  for (group = parser->groups; group < parser->egroup; group++)
1270  if (group->argp == argp)
1271  return group->input;
1272  }
1273 
1274  return 0;
1275 }
1276 #ifdef weak_alias
1277 weak_alias (__argp_input, _argp_input)
1278 #endif
1279 
1280 /* Defined here, in case a user is not inlining the definitions in
1281  * argp.h */
1282 void
1283 __argp_usage (__const struct argp_state *__state)
1284 {
1285  __argp_state_help (__state, stderr, ARGP_HELP_STD_USAGE);
1286 }
1287 
1288 int
1289 __option_is_short (__const struct argp_option *__opt)
1290 {
1291  if (__opt->flags & OPTION_DOC)
1292  return 0;
1293  else
1294  {
1295  int __key = __opt->key;
1296  /* FIXME: whether or not a particular key implies a short option
1297  * ought not to be locale dependent. */
1298  return __key > 0 && isprint (__key);
1299  }
1300 }
1301 
1302 int
1303 __option_is_end (__const struct argp_option *__opt)
1304 {
1305  return !__opt->key && !__opt->name && !__opt->doc && !__opt->group;
1306 }
parser
Definition: argp-parse.c:246
argp
Definition: argp.h:212
parser_convert_state
Definition: argp-parse.c:427
argp_state
Definition: argp.h:302
group
Definition: argp-parse.c:204
argp_option
Definition: argp.h:73
parser_sizes
Definition: argp-parse.c:514
argp_child
Definition: argp.h:277