fixup gcc warnings
[uclibc-ng.git] / libuargp / argp-parse.c
blob912e3e2ab4b3ee529f72b3d5fa7288d92bb861ac
1 /* Hierarchial argument parsing, layered over getopt
2 Copyright (C) 1995-2000, 2002, 2003, 2004 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Written by Miles Bader <miles at gnu.ai.mit.edu>.
6 The GNU C Library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the License, or (at your option) any later version.
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 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public
17 License along with the GNU C Library; see the file COPYING.LIB. If
18 not, see <http://www.gnu.org/licenses/>.
20 Modified for uClibc by: Salvatore Cro <salvatore.cro at st.com>
23 #ifdef HAVE_CONFIG_H
24 #include <config.h>
25 #endif
27 /* AIX requires this to be the first thing in the file. */
28 #ifndef __GNUC__
29 # if HAVE_ALLOCA_H || defined _LIBC
30 # include <alloca.h>
31 # else
32 # ifdef _AIX
33 #pragma alloca
34 # else
35 # ifndef alloca /* predefined by HP cc +Olibcalls */
36 char *alloca ();
37 # endif
38 # endif
39 # endif
40 #endif
42 #include <stdlib.h>
43 #include <string.h>
44 #include <unistd.h>
45 #include <limits.h>
46 #include <getopt.h>
47 #include <bits/getopt_int.h>
49 #include <features.h>
50 #ifndef _
51 /* This is for other GNU distributions with internationalized messages.
52 When compiling libc, the _ macro is predefined. */
53 # if (defined HAVE_LIBINTL_H || defined _LIBC) && defined __UCLIBC_HAS_GETTEXT_AWARENESS__
54 # include <libintl.h>
55 # ifdef _LIBC
56 # undef dgettext
57 # define dgettext(domain, msgid) \
58 INTUSE(__dcgettext) (domain, msgid, LC_MESSAGES)
59 # endif
60 # else
61 # define dgettext(domain, msgid) (msgid)
62 # define gettext(msgid) (msgid)
63 # endif
64 #endif
65 #ifndef N_
66 # define N_(msgid) (msgid)
67 #endif
69 #include <argp.h>
71 /* Getopt return values. */
72 #define KEY_END (-1) /* The end of the options. */
73 #define KEY_ARG 1 /* A non-option argument. */
74 #define KEY_ERR '?' /* An error parsing the options. */
76 /* The meta-argument used to prevent any further arguments being interpreted
77 as options. */
78 #define QUOTE "--"
80 /* The number of bits we steal in a long-option value for our own use. */
81 #define GROUP_BITS CHAR_BIT
83 /* The number of bits available for the user value. */
84 #define USER_BITS ((sizeof ((struct option *)0)->val * CHAR_BIT) - GROUP_BITS)
85 #define USER_MASK ((1 << USER_BITS) - 1)
87 /* EZ alias for ARGP_ERR_UNKNOWN. */
88 #define EBADKEY ARGP_ERR_UNKNOWN
90 /* Default options. */
92 /* When argp is given the --HANG switch, _ARGP_HANG is set and argp will sleep
93 for one second intervals, decrementing _ARGP_HANG until it's zero. Thus
94 you can force the program to continue by attaching a debugger and setting
95 it to 0 yourself. */
96 static volatile int _argp_hang;
98 #define OPT_PROGNAME -2
99 #define OPT_USAGE -3
100 #define OPT_HANG -4
102 static const struct argp_option argp_default_options[] =
104 {"help", '?', 0, 0, N_("Give this help list"), -1},
105 {"usage", OPT_USAGE, 0, 0, N_("Give a short usage message")},
106 {"program-name",OPT_PROGNAME,"NAME", OPTION_HIDDEN, N_("Set the program name")},
107 {"HANG", OPT_HANG, "SECS", OPTION_ARG_OPTIONAL | OPTION_HIDDEN,
108 N_("Hang for SECS seconds (default 3600)")},
109 {0, 0}
112 static error_t
113 argp_default_parser (int key, char *arg, struct argp_state *state)
115 switch (key)
117 case '?':
118 argp_state_help (state, state->out_stream, ARGP_HELP_STD_HELP);
119 break;
120 case OPT_USAGE:
121 argp_state_help (state, state->out_stream,
122 ARGP_HELP_USAGE | ARGP_HELP_EXIT_OK);
123 break;
125 case OPT_PROGNAME: /* Set the program name. */
126 #if defined _LIBC || HAVE_DECL_PROGRAM_INVOCATION_NAME
127 program_invocation_name = arg;
128 #endif
129 /* [Note that some systems only have PROGRAM_INVOCATION_SHORT_NAME (aka
130 __PROGNAME), in which case, PROGRAM_INVOCATION_NAME is just defined
131 to be that, so we have to be a bit careful here.] */
133 /* Update what we use for messages. */
134 state->name = strrchr (arg, '/');
135 if (state->name)
136 state->name++;
137 else
138 state->name = arg;
140 #if defined _LIBC || HAVE_DECL_PROGRAM_INVOCATION_SHORT_NAME
141 program_invocation_short_name = state->name;
142 #endif
144 if ((state->flags & (ARGP_PARSE_ARGV0 | ARGP_NO_ERRS))
145 == ARGP_PARSE_ARGV0)
146 /* Update what getopt uses too. */
147 state->argv[0] = arg;
149 break;
151 case OPT_HANG:
152 _argp_hang = atoi (arg ? arg : "3600");
153 while (_argp_hang-- > 0)
154 sleep (1);
155 break;
157 default:
158 return EBADKEY;
160 return 0;
163 static const struct argp argp_default_argp =
164 {argp_default_options, &argp_default_parser, NULL, NULL, NULL, NULL, "libc"};
167 static const struct argp_option argp_version_options[] =
169 {"version", 'V', 0, 0, N_("Print program version"), -1},
170 {0, 0}
173 static error_t
174 argp_version_parser (int key, char *arg, struct argp_state *state)
176 switch (key)
178 case 'V':
179 if (argp_program_version_hook)
180 (*argp_program_version_hook) (state->out_stream, state);
181 else if (argp_program_version)
182 fprintf (state->out_stream, "%s\n", argp_program_version);
183 else
184 argp_error (state, dgettext (state->root_argp->argp_domain,
185 "(PROGRAM ERROR) No version known!?"));
186 if (! (state->flags & ARGP_NO_EXIT))
187 exit (0);
188 break;
189 default:
190 return EBADKEY;
192 return 0;
195 static const struct argp argp_version_argp =
196 {argp_version_options, &argp_version_parser, NULL, NULL, NULL, NULL, "libc"};
198 /* Returns the offset into the getopt long options array LONG_OPTIONS of a
199 long option with called NAME, or -1 if none is found. Passing NULL as
200 NAME will return the number of options. */
201 static int
202 find_long_option (struct option *long_options, const char *name)
204 struct option *l = long_options;
205 while (l->name != NULL)
206 if (name != NULL && strcmp (l->name, name) == 0)
207 return l - long_options;
208 else
209 l++;
210 if (name == NULL)
211 return l - long_options;
212 else
213 return -1;
217 /* The state of a `group' during parsing. Each group corresponds to a
218 particular argp structure from the tree of such descending from the top
219 level argp passed to argp_parse. */
220 struct group
222 /* This group's parsing function. */
223 argp_parser_t parser;
225 /* Which argp this group is from. */
226 const struct argp *argp;
228 /* Points to the point in SHORT_OPTS corresponding to the end of the short
229 options for this group. We use it to determine from which group a
230 particular short options is from. */
231 char *short_end;
233 /* The number of non-option args sucessfully handled by this parser. */
234 unsigned args_processed;
236 /* This group's parser's parent's group. */
237 struct group *parent;
238 unsigned parent_index; /* And the our position in the parent. */
240 /* These fields are swapped into and out of the state structure when
241 calling this group's parser. */
242 void *input, **child_inputs;
243 void *hook;
246 /* Call GROUP's parser with KEY and ARG, swapping any group-specific info
247 from STATE before calling, and back into state afterwards. If GROUP has
248 no parser, EBADKEY is returned. */
249 static error_t
250 group_parse (struct group *group, struct argp_state *state, int key, char *arg)
252 if (group->parser)
254 error_t err;
255 state->hook = group->hook;
256 state->input = group->input;
257 state->child_inputs = group->child_inputs;
258 state->arg_num = group->args_processed;
259 err = (*group->parser)(key, arg, state);
260 group->hook = state->hook;
261 return err;
263 else
264 return EBADKEY;
267 struct parser
269 const struct argp *argp;
271 /* SHORT_OPTS is the getopt short options string for the union of all the
272 groups of options. */
273 char *short_opts;
274 /* LONG_OPTS is the array of getop long option structures for the union of
275 all the groups of options. */
276 struct option *long_opts;
277 /* OPT_DATA is the getopt data used for the re-entrant getopt. */
278 struct _getopt_data opt_data;
280 /* States of the various parsing groups. */
281 struct group *groups;
282 /* The end of the GROUPS array. */
283 struct group *egroup;
284 /* An vector containing storage for the CHILD_INPUTS field in all groups. */
285 void **child_inputs;
287 /* True if we think using getopt is still useful; if false, then
288 remaining arguments are just passed verbatim with ARGP_KEY_ARG. This is
289 cleared whenever getopt returns KEY_END, but may be set again if the user
290 moves the next argument pointer backwards. */
291 int try_getopt;
293 /* State block supplied to parsing routines. */
294 struct argp_state state;
296 /* Memory used by this parser. */
297 void *storage;
300 /* The next usable entries in the various parser tables being filled in by
301 convert_options. */
302 struct parser_convert_state
304 struct parser *parser;
305 char *short_end;
306 struct option *long_end;
307 void **child_inputs_end;
310 /* Converts all options in ARGP (which is put in GROUP) and ancestors
311 into getopt options stored in SHORT_OPTS and LONG_OPTS; SHORT_END and
312 CVT->LONG_END are the points at which new options are added. Returns the
313 next unused group entry. CVT holds state used during the conversion. */
314 static struct group *
315 convert_options (const struct argp *argp,
316 struct group *parent, unsigned parent_index,
317 struct group *group, struct parser_convert_state *cvt)
319 /* REAL is the most recent non-alias value of OPT. */
320 const struct argp_option *real = argp->options;
321 const struct argp_child *children = argp->children;
323 if (real || argp->parser)
325 const struct argp_option *opt;
327 if (real)
328 for (opt = real; !__option_is_end (opt); opt++)
330 if (! (opt->flags & OPTION_ALIAS))
331 /* OPT isn't an alias, so we can use values from it. */
332 real = opt;
334 if (! (real->flags & OPTION_DOC))
335 /* A real option (not just documentation). */
337 if (__option_is_short (opt))
338 /* OPT can be used as a short option. */
340 *cvt->short_end++ = opt->key;
341 if (real->arg)
343 *cvt->short_end++ = ':';
344 if (real->flags & OPTION_ARG_OPTIONAL)
345 *cvt->short_end++ = ':';
347 *cvt->short_end = '\0'; /* keep 0 terminated */
350 if (opt->name
351 && find_long_option (cvt->parser->long_opts, opt->name) < 0)
352 /* OPT can be used as a long option. */
354 cvt->long_end->name = opt->name;
355 cvt->long_end->has_arg =
356 (real->arg
357 ? (real->flags & OPTION_ARG_OPTIONAL
358 ? optional_argument
359 : required_argument)
360 : no_argument);
361 cvt->long_end->flag = 0;
362 /* we add a disambiguating code to all the user's
363 values (which is removed before we actually call
364 the function to parse the value); this means that
365 the user loses use of the high 8 bits in all his
366 values (the sign of the lower bits is preserved
367 however)... */
368 cvt->long_end->val =
369 ((opt->key | real->key) & USER_MASK)
370 + (((group - cvt->parser->groups) + 1) << USER_BITS);
372 /* Keep the LONG_OPTS list terminated. */
373 (++cvt->long_end)->name = NULL;
378 group->parser = argp->parser;
379 group->argp = argp;
380 group->short_end = cvt->short_end;
381 group->args_processed = 0;
382 group->parent = parent;
383 group->parent_index = parent_index;
384 group->input = 0;
385 group->hook = 0;
386 group->child_inputs = 0;
388 if (children)
389 /* Assign GROUP's CHILD_INPUTS field some space from
390 CVT->child_inputs_end.*/
392 unsigned num_children = 0;
393 while (children[num_children].argp)
394 num_children++;
395 group->child_inputs = cvt->child_inputs_end;
396 cvt->child_inputs_end += num_children;
399 parent = group++;
401 else
402 parent = 0;
404 if (children)
406 unsigned index = 0;
407 while (children->argp)
408 group =
409 convert_options (children++->argp, parent, index++, group, cvt);
412 return group;
415 /* Find the merged set of getopt options, with keys appropiately prefixed. */
416 static void
417 parser_convert (struct parser *parser, const struct argp *argp, int flags)
419 struct parser_convert_state cvt;
421 cvt.parser = parser;
422 cvt.short_end = parser->short_opts;
423 cvt.long_end = parser->long_opts;
424 cvt.child_inputs_end = parser->child_inputs;
426 if (flags & ARGP_IN_ORDER)
427 *cvt.short_end++ = '-';
428 else if (flags & ARGP_NO_ARGS)
429 *cvt.short_end++ = '+';
430 *cvt.short_end = '\0';
432 cvt.long_end->name = NULL;
434 parser->argp = argp;
436 if (argp)
437 parser->egroup = convert_options (argp, 0, 0, parser->groups, &cvt);
438 else
439 parser->egroup = parser->groups; /* No parsers at all! */
442 /* Lengths of various parser fields which we will allocated. */
443 struct parser_sizes
445 size_t short_len; /* Getopt short options string. */
446 size_t long_len; /* Getopt long options vector. */
447 size_t num_groups; /* Group structures we allocate. */
448 size_t num_child_inputs; /* Child input slots. */
451 /* For ARGP, increments the NUM_GROUPS field in SZS by the total number of
452 argp structures descended from it, and the SHORT_LEN & LONG_LEN fields by
453 the maximum lengths of the resulting merged getopt short options string and
454 long-options array, respectively. */
455 static void
456 calc_sizes (const struct argp *argp, struct parser_sizes *szs)
458 const struct argp_child *child = argp->children;
459 const struct argp_option *opt = argp->options;
461 if (opt || argp->parser)
463 szs->num_groups++;
464 if (opt)
466 int num_opts = 0;
467 while (!__option_is_end (opt++))
468 num_opts++;
469 szs->short_len += num_opts * 3; /* opt + up to 2 `:'s */
470 szs->long_len += num_opts;
474 if (child)
475 while (child->argp)
477 calc_sizes ((child++)->argp, szs);
478 szs->num_child_inputs++;
483 extern char * __argp_short_program_name (void);
484 /* Initializes PARSER to parse ARGP in a manner described by FLAGS. */
485 static error_t
486 parser_init (struct parser *parser, const struct argp *argp,
487 int argc, char **argv, int flags, void *input)
489 error_t err = 0;
490 struct group *group;
491 struct parser_sizes szs;
492 struct _getopt_data opt_data = _GETOPT_DATA_INITIALIZER;
494 szs.short_len = (flags & ARGP_NO_ARGS) ? 0 : 1;
495 szs.long_len = 0;
496 szs.num_groups = 0;
497 szs.num_child_inputs = 0;
499 if (argp)
500 calc_sizes (argp, &szs);
502 /* Lengths of the various bits of storage used by PARSER. */
503 #define GLEN (szs.num_groups + 1) * sizeof (struct group)
504 #define CLEN (szs.num_child_inputs * sizeof (void *))
505 #define LLEN ((szs.long_len + 1) * sizeof (struct option))
506 #define SLEN (szs.short_len + 1)
508 parser->storage = malloc (GLEN + CLEN + LLEN + SLEN);
509 if (! parser->storage)
510 return ENOMEM;
512 parser->groups = parser->storage;
513 parser->child_inputs = parser->storage + GLEN;
514 parser->long_opts = parser->storage + GLEN + CLEN;
515 parser->short_opts = parser->storage + GLEN + CLEN + LLEN;
516 parser->opt_data = opt_data;
518 memset (parser->child_inputs, 0, szs.num_child_inputs * sizeof (void *));
519 parser_convert (parser, argp, flags);
521 memset (&parser->state, 0, sizeof (struct argp_state));
522 parser->state.root_argp = parser->argp;
523 parser->state.argc = argc;
524 parser->state.argv = argv;
525 parser->state.flags = flags;
526 parser->state.err_stream = stderr;
527 parser->state.out_stream = stdout;
528 parser->state.next = 0; /* Tell getopt to initialize. */
529 parser->state.pstate = parser;
531 parser->try_getopt = 1;
533 /* Call each parser for the first time, giving it a chance to propagate
534 values to child parsers. */
535 if (parser->groups < parser->egroup)
536 parser->groups->input = input;
537 for (group = parser->groups;
538 group < parser->egroup && (!err || err == EBADKEY);
539 group++)
541 if (group->parent)
542 /* If a child parser, get the initial input value from the parent. */
543 group->input = group->parent->child_inputs[group->parent_index];
545 if (!group->parser
546 && group->argp->children && group->argp->children->argp)
547 /* For the special case where no parsing function is supplied for an
548 argp, propagate its input to its first child, if any (this just
549 makes very simple wrapper argps more convenient). */
550 group->child_inputs[0] = group->input;
552 err = group_parse (group, &parser->state, ARGP_KEY_INIT, 0);
554 if (err == EBADKEY)
555 err = 0; /* Some parser didn't understand. */
557 if (err)
558 return err;
560 if (parser->state.flags & ARGP_NO_ERRS)
562 parser->opt_data.opterr = 0;
563 if (parser->state.flags & ARGP_PARSE_ARGV0)
564 /* getopt always skips ARGV[0], so we have to fake it out. As long
565 as OPTERR is 0, then it shouldn't actually try to access it. */
566 parser->state.argv--, parser->state.argc++;
568 else
569 parser->opt_data.opterr = 1; /* Print error messages. */
571 if (parser->state.argv == argv && argv[0])
572 /* There's an argv[0]; use it for messages. */
574 char *short_name = strrchr (argv[0], '/');
575 parser->state.name = short_name ? short_name + 1 : argv[0];
577 else
578 parser->state.name = __argp_short_program_name ();
580 return 0;
583 /* Free any storage consumed by PARSER (but not PARSER itself). */
584 static error_t
585 parser_finalize (struct parser *parser,
586 error_t err, int arg_ebadkey, int *end_index)
588 struct group *group;
590 if (err == EBADKEY && arg_ebadkey)
591 /* Suppress errors generated by unparsed arguments. */
592 err = 0;
594 if (! err)
596 if (parser->state.next == parser->state.argc)
597 /* We successfully parsed all arguments! Call all the parsers again,
598 just a few more times... */
600 for (group = parser->groups;
601 group < parser->egroup && (!err || err==EBADKEY);
602 group++)
603 if (group->args_processed == 0)
604 err = group_parse (group, &parser->state, ARGP_KEY_NO_ARGS, 0);
605 for (group = parser->egroup - 1;
606 group >= parser->groups && (!err || err==EBADKEY);
607 group--)
608 err = group_parse (group, &parser->state, ARGP_KEY_END, 0);
610 if (err == EBADKEY)
611 err = 0; /* Some parser didn't understand. */
613 /* Tell the user that all arguments are parsed. */
614 if (end_index)
615 *end_index = parser->state.next;
617 else if (end_index)
618 /* Return any remaining arguments to the user. */
619 *end_index = parser->state.next;
620 else
621 /* No way to return the remaining arguments, they must be bogus. */
623 if (!(parser->state.flags & ARGP_NO_ERRS)
624 && parser->state.err_stream)
625 fprintf (parser->state.err_stream,
626 dgettext (parser->argp->argp_domain,
627 "%s: Too many arguments\n"),
628 parser->state.name);
629 err = EBADKEY;
633 /* Okay, we're all done, with either an error or success; call the parsers
634 to indicate which one. */
636 if (err)
638 /* Maybe print an error message. */
639 if (err == EBADKEY)
640 /* An appropriate message describing what the error was should have
641 been printed earlier. */
642 argp_state_help (&parser->state, parser->state.err_stream,
643 ARGP_HELP_STD_ERR);
645 /* Since we didn't exit, give each parser an error indication. */
646 for (group = parser->groups; group < parser->egroup; group++)
647 group_parse (group, &parser->state, ARGP_KEY_ERROR, 0);
649 else
650 /* Notify parsers of success, and propagate back values from parsers. */
652 /* We pass over the groups in reverse order so that child groups are
653 given a chance to do there processing before passing back a value to
654 the parent. */
655 for (group = parser->egroup - 1
656 ; group >= parser->groups && (!err || err == EBADKEY)
657 ; group--)
658 err = group_parse (group, &parser->state, ARGP_KEY_SUCCESS, 0);
659 if (err == EBADKEY)
660 err = 0; /* Some parser didn't understand. */
663 /* Call parsers once more, to do any final cleanup. Errors are ignored. */
664 for (group = parser->egroup - 1; group >= parser->groups; group--)
665 group_parse (group, &parser->state, ARGP_KEY_FINI, 0);
667 if (err == EBADKEY)
668 err = EINVAL;
670 free (parser->storage);
672 return err;
675 /* Call the user parsers to parse the non-option argument VAL, at the current
676 position, returning any error. The state NEXT pointer is assumed to have
677 been adjusted (by getopt) to point after this argument; this function will
678 adjust it correctly to reflect however many args actually end up being
679 consumed. */
680 static error_t
681 parser_parse_arg (struct parser *parser, char *val)
683 /* Save the starting value of NEXT, first adjusting it so that the arg
684 we're parsing is again the front of the arg vector. */
685 int index = --parser->state.next;
686 error_t err = EBADKEY;
687 struct group *group;
688 int key = 0; /* Which of ARGP_KEY_ARG[S] we used. */
690 /* Try to parse the argument in each parser. */
691 for (group = parser->groups
692 ; group < parser->egroup && err == EBADKEY
693 ; group++)
695 parser->state.next++; /* For ARGP_KEY_ARG, consume the arg. */
696 key = ARGP_KEY_ARG;
697 err = group_parse (group, &parser->state, key, val);
699 if (err == EBADKEY)
700 /* This parser doesn't like ARGP_KEY_ARG; try ARGP_KEY_ARGS instead. */
702 parser->state.next--; /* For ARGP_KEY_ARGS, put back the arg. */
703 key = ARGP_KEY_ARGS;
704 err = group_parse (group, &parser->state, key, 0);
708 if (! err)
710 if (key == ARGP_KEY_ARGS)
711 /* The default for ARGP_KEY_ARGS is to assume that if NEXT isn't
712 changed by the user, *all* arguments should be considered
713 consumed. */
714 parser->state.next = parser->state.argc;
716 if (parser->state.next > index)
717 /* Remember that we successfully processed a non-option
718 argument -- but only if the user hasn't gotten tricky and set
719 the clock back. */
720 (--group)->args_processed += (parser->state.next - index);
721 else
722 /* The user wants to reparse some args, give getopt another try. */
723 parser->try_getopt = 1;
726 return err;
729 /* Call the user parsers to parse the option OPT, with argument VAL, at the
730 current position, returning any error. */
731 static error_t
732 parser_parse_opt (struct parser *parser, int opt, char *val)
734 /* The group key encoded in the high bits; 0 for short opts or
735 group_number + 1 for long opts. */
736 int group_key = opt >> USER_BITS;
737 error_t err = EBADKEY;
739 if (group_key == 0)
740 /* A short option. By comparing OPT's position in SHORT_OPTS to the
741 various starting positions in each group's SHORT_END field, we can
742 determine which group OPT came from. */
744 struct group *group;
745 char *short_index = strchr (parser->short_opts, opt);
747 if (short_index)
748 for (group = parser->groups; group < parser->egroup; group++)
749 if (group->short_end > short_index)
751 err = group_parse (group, &parser->state, opt,
752 parser->opt_data.optarg);
753 break;
756 else
757 /* A long option. We use shifts instead of masking for extracting
758 the user value in order to preserve the sign. */
759 err =
760 group_parse (&parser->groups[group_key - 1], &parser->state,
761 (opt << GROUP_BITS) >> GROUP_BITS,
762 parser->opt_data.optarg);
764 if (err == EBADKEY)
765 /* At least currently, an option not recognized is an error in the
766 parser, because we pre-compute which parser is supposed to deal
767 with each option. */
769 static const char bad_key_err[] =
770 N_("(PROGRAM ERROR) Option should have been recognized!?");
771 if (group_key == 0)
772 argp_error (&parser->state, "-%c: %s", opt,
773 dgettext (parser->argp->argp_domain, bad_key_err));
774 else
776 struct option *long_opt = parser->long_opts;
777 while (long_opt->val != opt && long_opt->name)
778 long_opt++;
779 argp_error (&parser->state, "--%s: %s",
780 long_opt->name ? long_opt->name : "???",
781 dgettext (parser->argp->argp_domain, bad_key_err));
785 return err;
788 /* Parse the next argument in PARSER (as indicated by PARSER->state.next).
789 Any error from the parsers is returned, and *ARGP_EBADKEY indicates
790 whether a value of EBADKEY is due to an unrecognized argument (which is
791 generally not fatal). */
792 static error_t
793 parser_parse_next (struct parser *parser, int *arg_ebadkey)
795 int opt;
796 error_t err = 0;
798 if (parser->state.quoted && parser->state.next < parser->state.quoted)
799 /* The next argument pointer has been moved to before the quoted
800 region, so pretend we never saw the quoting `--', and give getopt
801 another chance. If the user hasn't removed it, getopt will just
802 process it again. */
803 parser->state.quoted = 0;
805 if (parser->try_getopt && !parser->state.quoted)
806 /* Give getopt a chance to parse this. */
808 /* Put it back in OPTIND for getopt. */
809 parser->opt_data.optind = parser->state.next;
810 /* Distinguish KEY_ERR from a real option. */
811 parser->opt_data.optopt = KEY_END;
812 if (parser->state.flags & ARGP_LONG_ONLY)
813 opt = _getopt_long_only_r (parser->state.argc, parser->state.argv,
814 parser->short_opts, parser->long_opts, 0,
815 &parser->opt_data);
816 else
817 opt = _getopt_long_r (parser->state.argc, parser->state.argv,
818 parser->short_opts, parser->long_opts, 0,
819 &parser->opt_data);
820 /* And see what getopt did. */
821 parser->state.next = parser->opt_data.optind;
823 if (opt == KEY_END)
824 /* Getopt says there are no more options, so stop using
825 getopt; we'll continue if necessary on our own. */
827 parser->try_getopt = 0;
828 if (parser->state.next > 1
829 && strcmp (parser->state.argv[parser->state.next - 1], QUOTE)
830 == 0)
831 /* Not only is this the end of the options, but it's a
832 `quoted' region, which may have args that *look* like
833 options, so we definitely shouldn't try to use getopt past
834 here, whatever happens. */
835 parser->state.quoted = parser->state.next;
837 else if (opt == KEY_ERR && parser->opt_data.optopt != KEY_END)
838 /* KEY_ERR can have the same value as a valid user short
839 option, but in the case of a real error, getopt sets OPTOPT
840 to the offending character, which can never be KEY_END. */
842 *arg_ebadkey = 0;
843 return EBADKEY;
846 else
847 opt = KEY_END;
849 if (opt == KEY_END)
851 /* We're past what getopt considers the options. */
852 if (parser->state.next >= parser->state.argc
853 || (parser->state.flags & ARGP_NO_ARGS))
854 /* Indicate that we're done. */
856 *arg_ebadkey = 1;
857 return EBADKEY;
859 else
860 /* A non-option arg; simulate what getopt might have done. */
862 opt = KEY_ARG;
863 parser->opt_data.optarg = parser->state.argv[parser->state.next++];
867 if (opt == KEY_ARG)
868 /* A non-option argument; try each parser in turn. */
869 err = parser_parse_arg (parser, parser->opt_data.optarg);
870 else
871 err = parser_parse_opt (parser, opt, parser->opt_data.optarg);
873 if (err == EBADKEY)
874 *arg_ebadkey = (opt == KEY_END || opt == KEY_ARG);
876 return err;
879 /* Parse the options strings in ARGC & ARGV according to the argp in ARGP.
880 FLAGS is one of the ARGP_ flags above. If END_INDEX is non-NULL, the
881 index in ARGV of the first unparsed option is returned in it. If an
882 unknown option is present, EINVAL is returned; if some parser routine
883 returned a non-zero value, it is returned; otherwise 0 is returned. */
884 error_t
885 argp_parse (const struct argp *argp, int argc, char **argv, unsigned flags,
886 int *end_index, void *input)
888 error_t err;
889 struct parser parser;
891 /* If true, then err == EBADKEY is a result of a non-option argument failing
892 to be parsed (which in some cases isn't actually an error). */
893 int arg_ebadkey = 0;
895 if (! (flags & ARGP_NO_HELP))
896 /* Add our own options. */
898 struct argp_child *child = alloca (4 * sizeof (struct argp_child));
899 struct argp *top_argp = alloca (sizeof (struct argp));
901 /* TOP_ARGP has no options, it just serves to group the user & default
902 argps. */
903 memset (top_argp, 0, sizeof (*top_argp));
904 top_argp->children = child;
906 memset (child, 0, 4 * sizeof (struct argp_child));
908 if (argp)
909 (child++)->argp = argp;
910 (child++)->argp = &argp_default_argp;
911 if (argp_program_version || argp_program_version_hook)
912 (child++)->argp = &argp_version_argp;
913 child->argp = 0;
915 argp = top_argp;
918 /* Construct a parser for these arguments. */
919 err = parser_init (&parser, argp, argc, argv, flags, input);
921 if (! err)
922 /* Parse! */
924 while (! err)
925 err = parser_parse_next (&parser, &arg_ebadkey);
926 err = parser_finalize (&parser, err, arg_ebadkey, end_index);
929 return err;
932 /* Return the input field for ARGP in the parser corresponding to STATE; used
933 by the help routines. */
934 void *
935 __argp_input (const struct argp *argp, const struct argp_state *state)
937 if (state)
939 struct group *group;
940 struct parser *parser = state->pstate;
942 for (group = parser->groups; group < parser->egroup; group++)
943 if (group->argp == argp)
944 return group->input;
947 return 0;