nios2: allow to build toolchain
[uclibc-ng.git] / libuargp / argp-parse.c
blob86b2b24ee852f9622a4e7a6c46cd8cb09142777e
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; if not, write to the Free
18 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
19 02111-1307 USA.
21 Modified for uClibc by: Salvatore Cro <salvatore.cro at st.com>
24 #ifdef HAVE_CONFIG_H
25 #include <config.h>
26 #endif
28 /* AIX requires this to be the first thing in the file. */
29 #ifndef __GNUC__
30 # if HAVE_ALLOCA_H || defined _LIBC
31 # include <alloca.h>
32 # else
33 # ifdef _AIX
34 #pragma alloca
35 # else
36 # ifndef alloca /* predefined by HP cc +Olibcalls */
37 char *alloca ();
38 # endif
39 # endif
40 # endif
41 #endif
43 #include <stdlib.h>
44 #include <string.h>
45 #include <unistd.h>
46 #include <limits.h>
47 #include <getopt.h>
48 #include <bits/getopt_int.h>
50 #include <features.h>
51 #ifndef _
52 /* This is for other GNU distributions with internationalized messages.
53 When compiling libc, the _ macro is predefined. */
54 # if (defined HAVE_LIBINTL_H || defined _LIBC) && defined __UCLIBC_HAS_GETTEXT_AWARENESS__
55 # include <libintl.h>
56 # ifdef _LIBC
57 # undef dgettext
58 # define dgettext(domain, msgid) \
59 INTUSE(__dcgettext) (domain, msgid, LC_MESSAGES)
60 # endif
61 # else
62 # define dgettext(domain, msgid) (msgid)
63 # define gettext(msgid) (msgid)
64 # endif
65 #endif
66 #ifndef N_
67 # define N_(msgid) (msgid)
68 #endif
70 #include <argp.h>
72 /* Getopt return values. */
73 #define KEY_END (-1) /* The end of the options. */
74 #define KEY_ARG 1 /* A non-option argument. */
75 #define KEY_ERR '?' /* An error parsing the options. */
77 /* The meta-argument used to prevent any further arguments being interpreted
78 as options. */
79 #define QUOTE "--"
81 /* The number of bits we steal in a long-option value for our own use. */
82 #define GROUP_BITS CHAR_BIT
84 /* The number of bits available for the user value. */
85 #define USER_BITS ((sizeof ((struct option *)0)->val * CHAR_BIT) - GROUP_BITS)
86 #define USER_MASK ((1 << USER_BITS) - 1)
88 /* EZ alias for ARGP_ERR_UNKNOWN. */
89 #define EBADKEY ARGP_ERR_UNKNOWN
91 /* Default options. */
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 static volatile int _argp_hang;
99 #define OPT_PROGNAME -2
100 #define OPT_USAGE -3
101 #define OPT_HANG -4
103 static const struct argp_option argp_default_options[] =
105 {"help", '?', 0, 0, N_("Give this help list"), -1},
106 {"usage", OPT_USAGE, 0, 0, N_("Give a short usage message")},
107 {"program-name",OPT_PROGNAME,"NAME", OPTION_HIDDEN, N_("Set the program name")},
108 {"HANG", OPT_HANG, "SECS", OPTION_ARG_OPTIONAL | OPTION_HIDDEN,
109 N_("Hang for SECS seconds (default 3600)")},
110 {0, 0}
113 static error_t
114 argp_default_parser (int key, char *arg, struct argp_state *state)
116 switch (key)
118 case '?':
119 argp_state_help (state, state->out_stream, ARGP_HELP_STD_HELP);
120 break;
121 case OPT_USAGE:
122 argp_state_help (state, state->out_stream,
123 ARGP_HELP_USAGE | ARGP_HELP_EXIT_OK);
124 break;
126 case OPT_PROGNAME: /* Set the program name. */
127 #if defined _LIBC || HAVE_DECL_PROGRAM_INVOCATION_NAME
128 program_invocation_name = arg;
129 #endif
130 /* [Note that some systems only have PROGRAM_INVOCATION_SHORT_NAME (aka
131 __PROGNAME), in which case, PROGRAM_INVOCATION_NAME is just defined
132 to be that, so we have to be a bit careful here.] */
134 /* Update what we use for messages. */
135 state->name = strrchr (arg, '/');
136 if (state->name)
137 state->name++;
138 else
139 state->name = arg;
141 #if defined _LIBC || HAVE_DECL_PROGRAM_INVOCATION_SHORT_NAME
142 program_invocation_short_name = state->name;
143 #endif
145 if ((state->flags & (ARGP_PARSE_ARGV0 | ARGP_NO_ERRS))
146 == ARGP_PARSE_ARGV0)
147 /* Update what getopt uses too. */
148 state->argv[0] = arg;
150 break;
152 case OPT_HANG:
153 _argp_hang = atoi (arg ? arg : "3600");
154 while (_argp_hang-- > 0)
155 sleep (1);
156 break;
158 default:
159 return EBADKEY;
161 return 0;
164 static const struct argp argp_default_argp =
165 {argp_default_options, &argp_default_parser, NULL, NULL, NULL, NULL, "libc"};
168 static const struct argp_option argp_version_options[] =
170 {"version", 'V', 0, 0, N_("Print program version"), -1},
171 {0, 0}
174 static error_t
175 argp_version_parser (int key, char *arg, struct argp_state *state)
177 switch (key)
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;
193 return 0;
196 static const struct argp argp_version_argp =
197 {argp_version_options, &argp_version_parser, NULL, NULL, NULL, NULL, "libc"};
199 /* Returns the offset into the getopt long options array LONG_OPTIONS of a
200 long option with called NAME, or -1 if none is found. Passing NULL as
201 NAME will return the number of options. */
202 static int
203 find_long_option (struct option *long_options, const char *name)
205 struct option *l = long_options;
206 while (l->name != NULL)
207 if (name != NULL && strcmp (l->name, name) == 0)
208 return l - long_options;
209 else
210 l++;
211 if (name == NULL)
212 return l - long_options;
213 else
214 return -1;
218 /* The state of a `group' during parsing. Each group corresponds to a
219 particular argp structure from the tree of such descending from the top
220 level argp passed to argp_parse. */
221 struct group
223 /* This group's parsing function. */
224 argp_parser_t parser;
226 /* Which argp this group is from. */
227 const struct argp *argp;
229 /* Points to the point in SHORT_OPTS corresponding to the end of the short
230 options for this group. We use it to determine from which group a
231 particular short options is from. */
232 char *short_end;
234 /* The number of non-option args sucessfully handled by this parser. */
235 unsigned args_processed;
237 /* This group's parser's parent's group. */
238 struct group *parent;
239 unsigned parent_index; /* And the our position in the parent. */
241 /* These fields are swapped into and out of the state structure when
242 calling this group's parser. */
243 void *input, **child_inputs;
244 void *hook;
247 /* Call GROUP's parser with KEY and ARG, swapping any group-specific info
248 from STATE before calling, and back into state afterwards. If GROUP has
249 no parser, EBADKEY is returned. */
250 static error_t
251 group_parse (struct group *group, struct argp_state *state, int key, char *arg)
253 if (group->parser)
255 error_t err;
256 state->hook = group->hook;
257 state->input = group->input;
258 state->child_inputs = group->child_inputs;
259 state->arg_num = group->args_processed;
260 err = (*group->parser)(key, arg, state);
261 group->hook = state->hook;
262 return err;
264 else
265 return EBADKEY;
268 struct parser
270 const struct argp *argp;
272 /* SHORT_OPTS is the getopt short options string for the union of all the
273 groups of options. */
274 char *short_opts;
275 /* LONG_OPTS is the array of getop long option structures for the union of
276 all the groups of options. */
277 struct option *long_opts;
278 /* OPT_DATA is the getopt data used for the re-entrant getopt. */
279 struct _getopt_data opt_data;
281 /* States of the various parsing groups. */
282 struct group *groups;
283 /* The end of the GROUPS array. */
284 struct group *egroup;
285 /* An vector containing storage for the CHILD_INPUTS field in all groups. */
286 void **child_inputs;
288 /* True if we think using getopt is still useful; if false, then
289 remaining arguments are just passed verbatim with ARGP_KEY_ARG. This is
290 cleared whenever getopt returns KEY_END, but may be set again if the user
291 moves the next argument pointer backwards. */
292 int try_getopt;
294 /* State block supplied to parsing routines. */
295 struct argp_state state;
297 /* Memory used by this parser. */
298 void *storage;
301 /* The next usable entries in the various parser tables being filled in by
302 convert_options. */
303 struct parser_convert_state
305 struct parser *parser;
306 char *short_end;
307 struct option *long_end;
308 void **child_inputs_end;
311 /* Converts all options in ARGP (which is put in GROUP) and ancestors
312 into getopt options stored in SHORT_OPTS and LONG_OPTS; SHORT_END and
313 CVT->LONG_END are the points at which new options are added. Returns the
314 next unused group entry. CVT holds state used during the conversion. */
315 static struct group *
316 convert_options (const struct argp *argp,
317 struct group *parent, unsigned parent_index,
318 struct group *group, struct parser_convert_state *cvt)
320 /* REAL is the most recent non-alias value of OPT. */
321 const struct argp_option *real = argp->options;
322 const struct argp_child *children = argp->children;
324 if (real || argp->parser)
326 const struct argp_option *opt;
328 if (real)
329 for (opt = real; !__option_is_end (opt); opt++)
331 if (! (opt->flags & OPTION_ALIAS))
332 /* OPT isn't an alias, so we can use values from it. */
333 real = opt;
335 if (! (real->flags & OPTION_DOC))
336 /* A real option (not just documentation). */
338 if (__option_is_short (opt))
339 /* OPT can be used as a short option. */
341 *cvt->short_end++ = opt->key;
342 if (real->arg)
344 *cvt->short_end++ = ':';
345 if (real->flags & OPTION_ARG_OPTIONAL)
346 *cvt->short_end++ = ':';
348 *cvt->short_end = '\0'; /* keep 0 terminated */
351 if (opt->name
352 && find_long_option (cvt->parser->long_opts, opt->name) < 0)
353 /* OPT can be used as a long option. */
355 cvt->long_end->name = opt->name;
356 cvt->long_end->has_arg =
357 (real->arg
358 ? (real->flags & OPTION_ARG_OPTIONAL
359 ? optional_argument
360 : required_argument)
361 : no_argument);
362 cvt->long_end->flag = 0;
363 /* we add a disambiguating code to all the user's
364 values (which is removed before we actually call
365 the function to parse the value); this means that
366 the user loses use of the high 8 bits in all his
367 values (the sign of the lower bits is preserved
368 however)... */
369 cvt->long_end->val =
370 ((opt->key | real->key) & USER_MASK)
371 + (((group - cvt->parser->groups) + 1) << USER_BITS);
373 /* Keep the LONG_OPTS list terminated. */
374 (++cvt->long_end)->name = NULL;
379 group->parser = argp->parser;
380 group->argp = argp;
381 group->short_end = cvt->short_end;
382 group->args_processed = 0;
383 group->parent = parent;
384 group->parent_index = parent_index;
385 group->input = 0;
386 group->hook = 0;
387 group->child_inputs = 0;
389 if (children)
390 /* Assign GROUP's CHILD_INPUTS field some space from
391 CVT->child_inputs_end.*/
393 unsigned num_children = 0;
394 while (children[num_children].argp)
395 num_children++;
396 group->child_inputs = cvt->child_inputs_end;
397 cvt->child_inputs_end += num_children;
400 parent = group++;
402 else
403 parent = 0;
405 if (children)
407 unsigned index = 0;
408 while (children->argp)
409 group =
410 convert_options (children++->argp, parent, index++, group, cvt);
413 return group;
416 /* Find the merged set of getopt options, with keys appropiately prefixed. */
417 static void
418 parser_convert (struct parser *parser, const struct argp *argp, int flags)
420 struct parser_convert_state cvt;
422 cvt.parser = parser;
423 cvt.short_end = parser->short_opts;
424 cvt.long_end = parser->long_opts;
425 cvt.child_inputs_end = parser->child_inputs;
427 if (flags & ARGP_IN_ORDER)
428 *cvt.short_end++ = '-';
429 else if (flags & ARGP_NO_ARGS)
430 *cvt.short_end++ = '+';
431 *cvt.short_end = '\0';
433 cvt.long_end->name = NULL;
435 parser->argp = argp;
437 if (argp)
438 parser->egroup = convert_options (argp, 0, 0, parser->groups, &cvt);
439 else
440 parser->egroup = parser->groups; /* No parsers at all! */
443 /* Lengths of various parser fields which we will allocated. */
444 struct parser_sizes
446 size_t short_len; /* Getopt short options string. */
447 size_t long_len; /* Getopt long options vector. */
448 size_t num_groups; /* Group structures we allocate. */
449 size_t num_child_inputs; /* Child input slots. */
452 /* For ARGP, increments the NUM_GROUPS field in SZS by the total number of
453 argp structures descended from it, and the SHORT_LEN & LONG_LEN fields by
454 the maximum lengths of the resulting merged getopt short options string and
455 long-options array, respectively. */
456 static void
457 calc_sizes (const struct argp *argp, struct parser_sizes *szs)
459 const struct argp_child *child = argp->children;
460 const struct argp_option *opt = argp->options;
462 if (opt || argp->parser)
464 szs->num_groups++;
465 if (opt)
467 int num_opts = 0;
468 while (!__option_is_end (opt++))
469 num_opts++;
470 szs->short_len += num_opts * 3; /* opt + up to 2 `:'s */
471 szs->long_len += num_opts;
475 if (child)
476 while (child->argp)
478 calc_sizes ((child++)->argp, szs);
479 szs->num_child_inputs++;
484 extern char * __argp_short_program_name (void);
485 /* Initializes PARSER to parse ARGP in a manner described by FLAGS. */
486 static error_t
487 parser_init (struct parser *parser, const struct argp *argp,
488 int argc, char **argv, int flags, void *input)
490 error_t err = 0;
491 struct group *group;
492 struct parser_sizes szs;
493 struct _getopt_data opt_data = _GETOPT_DATA_INITIALIZER;
495 szs.short_len = (flags & ARGP_NO_ARGS) ? 0 : 1;
496 szs.long_len = 0;
497 szs.num_groups = 0;
498 szs.num_child_inputs = 0;
500 if (argp)
501 calc_sizes (argp, &szs);
503 /* Lengths of the various bits of storage used by PARSER. */
504 #define GLEN (szs.num_groups + 1) * sizeof (struct group)
505 #define CLEN (szs.num_child_inputs * sizeof (void *))
506 #define LLEN ((szs.long_len + 1) * sizeof (struct option))
507 #define SLEN (szs.short_len + 1)
509 parser->storage = malloc (GLEN + CLEN + LLEN + SLEN);
510 if (! parser->storage)
511 return ENOMEM;
513 parser->groups = parser->storage;
514 parser->child_inputs = parser->storage + GLEN;
515 parser->long_opts = parser->storage + GLEN + CLEN;
516 parser->short_opts = parser->storage + GLEN + CLEN + LLEN;
517 parser->opt_data = opt_data;
519 memset (parser->child_inputs, 0, szs.num_child_inputs * sizeof (void *));
520 parser_convert (parser, argp, flags);
522 memset (&parser->state, 0, sizeof (struct argp_state));
523 parser->state.root_argp = parser->argp;
524 parser->state.argc = argc;
525 parser->state.argv = argv;
526 parser->state.flags = flags;
527 parser->state.err_stream = stderr;
528 parser->state.out_stream = stdout;
529 parser->state.next = 0; /* Tell getopt to initialize. */
530 parser->state.pstate = parser;
532 parser->try_getopt = 1;
534 /* Call each parser for the first time, giving it a chance to propagate
535 values to child parsers. */
536 if (parser->groups < parser->egroup)
537 parser->groups->input = input;
538 for (group = parser->groups;
539 group < parser->egroup && (!err || err == EBADKEY);
540 group++)
542 if (group->parent)
543 /* If a child parser, get the initial input value from the parent. */
544 group->input = group->parent->child_inputs[group->parent_index];
546 if (!group->parser
547 && group->argp->children && group->argp->children->argp)
548 /* For the special case where no parsing function is supplied for an
549 argp, propagate its input to its first child, if any (this just
550 makes very simple wrapper argps more convenient). */
551 group->child_inputs[0] = group->input;
553 err = group_parse (group, &parser->state, ARGP_KEY_INIT, 0);
555 if (err == EBADKEY)
556 err = 0; /* Some parser didn't understand. */
558 if (err)
559 return err;
561 if (parser->state.flags & ARGP_NO_ERRS)
563 parser->opt_data.opterr = 0;
564 if (parser->state.flags & ARGP_PARSE_ARGV0)
565 /* getopt always skips ARGV[0], so we have to fake it out. As long
566 as OPTERR is 0, then it shouldn't actually try to access it. */
567 parser->state.argv--, parser->state.argc++;
569 else
570 parser->opt_data.opterr = 1; /* Print error messages. */
572 if (parser->state.argv == argv && argv[0])
573 /* There's an argv[0]; use it for messages. */
575 char *short_name = strrchr (argv[0], '/');
576 parser->state.name = short_name ? short_name + 1 : argv[0];
578 else
579 parser->state.name = __argp_short_program_name ();
581 return 0;
584 /* Free any storage consumed by PARSER (but not PARSER itself). */
585 static error_t
586 parser_finalize (struct parser *parser,
587 error_t err, int arg_ebadkey, int *end_index)
589 struct group *group;
591 if (err == EBADKEY && arg_ebadkey)
592 /* Suppress errors generated by unparsed arguments. */
593 err = 0;
595 if (! err)
597 if (parser->state.next == parser->state.argc)
598 /* We successfully parsed all arguments! Call all the parsers again,
599 just a few more times... */
601 for (group = parser->groups;
602 group < parser->egroup && (!err || err==EBADKEY);
603 group++)
604 if (group->args_processed == 0)
605 err = group_parse (group, &parser->state, ARGP_KEY_NO_ARGS, 0);
606 for (group = parser->egroup - 1;
607 group >= parser->groups && (!err || err==EBADKEY);
608 group--)
609 err = group_parse (group, &parser->state, ARGP_KEY_END, 0);
611 if (err == EBADKEY)
612 err = 0; /* Some parser didn't understand. */
614 /* Tell the user that all arguments are parsed. */
615 if (end_index)
616 *end_index = parser->state.next;
618 else if (end_index)
619 /* Return any remaining arguments to the user. */
620 *end_index = parser->state.next;
621 else
622 /* No way to return the remaining arguments, they must be bogus. */
624 if (!(parser->state.flags & ARGP_NO_ERRS)
625 && parser->state.err_stream)
626 fprintf (parser->state.err_stream,
627 dgettext (parser->argp->argp_domain,
628 "%s: Too many arguments\n"),
629 parser->state.name);
630 err = EBADKEY;
634 /* Okay, we're all done, with either an error or success; call the parsers
635 to indicate which one. */
637 if (err)
639 /* Maybe print an error message. */
640 if (err == EBADKEY)
641 /* An appropriate message describing what the error was should have
642 been printed earlier. */
643 argp_state_help (&parser->state, parser->state.err_stream,
644 ARGP_HELP_STD_ERR);
646 /* Since we didn't exit, give each parser an error indication. */
647 for (group = parser->groups; group < parser->egroup; group++)
648 group_parse (group, &parser->state, ARGP_KEY_ERROR, 0);
650 else
651 /* Notify parsers of success, and propagate back values from parsers. */
653 /* We pass over the groups in reverse order so that child groups are
654 given a chance to do there processing before passing back a value to
655 the parent. */
656 for (group = parser->egroup - 1
657 ; group >= parser->groups && (!err || err == EBADKEY)
658 ; group--)
659 err = group_parse (group, &parser->state, ARGP_KEY_SUCCESS, 0);
660 if (err == EBADKEY)
661 err = 0; /* Some parser didn't understand. */
664 /* Call parsers once more, to do any final cleanup. Errors are ignored. */
665 for (group = parser->egroup - 1; group >= parser->groups; group--)
666 group_parse (group, &parser->state, ARGP_KEY_FINI, 0);
668 if (err == EBADKEY)
669 err = EINVAL;
671 free (parser->storage);
673 return err;
676 /* Call the user parsers to parse the non-option argument VAL, at the current
677 position, returning any error. The state NEXT pointer is assumed to have
678 been adjusted (by getopt) to point after this argument; this function will
679 adjust it correctly to reflect however many args actually end up being
680 consumed. */
681 static error_t
682 parser_parse_arg (struct parser *parser, char *val)
684 /* Save the starting value of NEXT, first adjusting it so that the arg
685 we're parsing is again the front of the arg vector. */
686 int index = --parser->state.next;
687 error_t err = EBADKEY;
688 struct group *group;
689 int key = 0; /* Which of ARGP_KEY_ARG[S] we used. */
691 /* Try to parse the argument in each parser. */
692 for (group = parser->groups
693 ; group < parser->egroup && err == EBADKEY
694 ; group++)
696 parser->state.next++; /* For ARGP_KEY_ARG, consume the arg. */
697 key = ARGP_KEY_ARG;
698 err = group_parse (group, &parser->state, key, val);
700 if (err == EBADKEY)
701 /* This parser doesn't like ARGP_KEY_ARG; try ARGP_KEY_ARGS instead. */
703 parser->state.next--; /* For ARGP_KEY_ARGS, put back the arg. */
704 key = ARGP_KEY_ARGS;
705 err = group_parse (group, &parser->state, key, 0);
709 if (! err)
711 if (key == ARGP_KEY_ARGS)
712 /* The default for ARGP_KEY_ARGS is to assume that if NEXT isn't
713 changed by the user, *all* arguments should be considered
714 consumed. */
715 parser->state.next = parser->state.argc;
717 if (parser->state.next > index)
718 /* Remember that we successfully processed a non-option
719 argument -- but only if the user hasn't gotten tricky and set
720 the clock back. */
721 (--group)->args_processed += (parser->state.next - index);
722 else
723 /* The user wants to reparse some args, give getopt another try. */
724 parser->try_getopt = 1;
727 return err;
730 /* Call the user parsers to parse the option OPT, with argument VAL, at the
731 current position, returning any error. */
732 static error_t
733 parser_parse_opt (struct parser *parser, int opt, char *val)
735 /* The group key encoded in the high bits; 0 for short opts or
736 group_number + 1 for long opts. */
737 int group_key = opt >> USER_BITS;
738 error_t err = EBADKEY;
740 if (group_key == 0)
741 /* A short option. By comparing OPT's position in SHORT_OPTS to the
742 various starting positions in each group's SHORT_END field, we can
743 determine which group OPT came from. */
745 struct group *group;
746 char *short_index = strchr (parser->short_opts, opt);
748 if (short_index)
749 for (group = parser->groups; group < parser->egroup; group++)
750 if (group->short_end > short_index)
752 err = group_parse (group, &parser->state, opt,
753 parser->opt_data.optarg);
754 break;
757 else
758 /* A long option. We use shifts instead of masking for extracting
759 the user value in order to preserve the sign. */
760 err =
761 group_parse (&parser->groups[group_key - 1], &parser->state,
762 (opt << GROUP_BITS) >> GROUP_BITS,
763 parser->opt_data.optarg);
765 if (err == EBADKEY)
766 /* At least currently, an option not recognized is an error in the
767 parser, because we pre-compute which parser is supposed to deal
768 with each option. */
770 static const char bad_key_err[] =
771 N_("(PROGRAM ERROR) Option should have been recognized!?");
772 if (group_key == 0)
773 argp_error (&parser->state, "-%c: %s", opt,
774 dgettext (parser->argp->argp_domain, bad_key_err));
775 else
777 struct option *long_opt = parser->long_opts;
778 while (long_opt->val != opt && long_opt->name)
779 long_opt++;
780 argp_error (&parser->state, "--%s: %s",
781 long_opt->name ? long_opt->name : "???",
782 dgettext (parser->argp->argp_domain, bad_key_err));
786 return err;
789 /* Parse the next argument in PARSER (as indicated by PARSER->state.next).
790 Any error from the parsers is returned, and *ARGP_EBADKEY indicates
791 whether a value of EBADKEY is due to an unrecognized argument (which is
792 generally not fatal). */
793 static error_t
794 parser_parse_next (struct parser *parser, int *arg_ebadkey)
796 int opt;
797 error_t err = 0;
799 if (parser->state.quoted && parser->state.next < parser->state.quoted)
800 /* The next argument pointer has been moved to before the quoted
801 region, so pretend we never saw the quoting `--', and give getopt
802 another chance. If the user hasn't removed it, getopt will just
803 process it again. */
804 parser->state.quoted = 0;
806 if (parser->try_getopt && !parser->state.quoted)
807 /* Give getopt a chance to parse this. */
809 /* Put it back in OPTIND for getopt. */
810 parser->opt_data.optind = parser->state.next;
811 /* Distinguish KEY_ERR from a real option. */
812 parser->opt_data.optopt = KEY_END;
813 if (parser->state.flags & ARGP_LONG_ONLY)
814 opt = _getopt_long_only_r (parser->state.argc, parser->state.argv,
815 parser->short_opts, parser->long_opts, 0,
816 &parser->opt_data);
817 else
818 opt = _getopt_long_r (parser->state.argc, parser->state.argv,
819 parser->short_opts, parser->long_opts, 0,
820 &parser->opt_data);
821 /* And see what getopt did. */
822 parser->state.next = parser->opt_data.optind;
824 if (opt == KEY_END)
825 /* Getopt says there are no more options, so stop using
826 getopt; we'll continue if necessary on our own. */
828 parser->try_getopt = 0;
829 if (parser->state.next > 1
830 && strcmp (parser->state.argv[parser->state.next - 1], QUOTE)
831 == 0)
832 /* Not only is this the end of the options, but it's a
833 `quoted' region, which may have args that *look* like
834 options, so we definitely shouldn't try to use getopt past
835 here, whatever happens. */
836 parser->state.quoted = parser->state.next;
838 else if (opt == KEY_ERR && parser->opt_data.optopt != KEY_END)
839 /* KEY_ERR can have the same value as a valid user short
840 option, but in the case of a real error, getopt sets OPTOPT
841 to the offending character, which can never be KEY_END. */
843 *arg_ebadkey = 0;
844 return EBADKEY;
847 else
848 opt = KEY_END;
850 if (opt == KEY_END)
852 /* We're past what getopt considers the options. */
853 if (parser->state.next >= parser->state.argc
854 || (parser->state.flags & ARGP_NO_ARGS))
855 /* Indicate that we're done. */
857 *arg_ebadkey = 1;
858 return EBADKEY;
860 else
861 /* A non-option arg; simulate what getopt might have done. */
863 opt = KEY_ARG;
864 parser->opt_data.optarg = parser->state.argv[parser->state.next++];
868 if (opt == KEY_ARG)
869 /* A non-option argument; try each parser in turn. */
870 err = parser_parse_arg (parser, parser->opt_data.optarg);
871 else
872 err = parser_parse_opt (parser, opt, parser->opt_data.optarg);
874 if (err == EBADKEY)
875 *arg_ebadkey = (opt == KEY_END || opt == KEY_ARG);
877 return err;
880 /* Parse the options strings in ARGC & ARGV according to the argp in ARGP.
881 FLAGS is one of the ARGP_ flags above. If END_INDEX is non-NULL, the
882 index in ARGV of the first unparsed option is returned in it. If an
883 unknown option is present, EINVAL is returned; if some parser routine
884 returned a non-zero value, it is returned; otherwise 0 is returned. */
885 error_t
886 argp_parse (const struct argp *argp, int argc, char **argv, unsigned flags,
887 int *end_index, void *input)
889 error_t err;
890 struct parser parser;
892 /* If true, then err == EBADKEY is a result of a non-option argument failing
893 to be parsed (which in some cases isn't actually an error). */
894 int arg_ebadkey = 0;
896 if (! (flags & ARGP_NO_HELP))
897 /* Add our own options. */
899 struct argp_child *child = alloca (4 * sizeof (struct argp_child));
900 struct argp *top_argp = alloca (sizeof (struct argp));
902 /* TOP_ARGP has no options, it just serves to group the user & default
903 argps. */
904 memset (top_argp, 0, sizeof (*top_argp));
905 top_argp->children = child;
907 memset (child, 0, 4 * sizeof (struct argp_child));
909 if (argp)
910 (child++)->argp = argp;
911 (child++)->argp = &argp_default_argp;
912 if (argp_program_version || argp_program_version_hook)
913 (child++)->argp = &argp_version_argp;
914 child->argp = 0;
916 argp = top_argp;
919 /* Construct a parser for these arguments. */
920 err = parser_init (&parser, argp, argc, argv, flags, input);
922 if (! err)
923 /* Parse! */
925 while (! err)
926 err = parser_parse_next (&parser, &arg_ebadkey);
927 err = parser_finalize (&parser, err, arg_ebadkey, end_index);
930 return err;
933 /* Return the input field for ARGP in the parser corresponding to STATE; used
934 by the help routines. */
935 void *
936 __argp_input (const struct argp *argp, const struct argp_state *state)
938 if (state)
940 struct group *group;
941 struct parser *parser = state->pstate;
943 for (group = parser->groups; group < parser->egroup; group++)
944 if (group->argp == argp)
945 return group->input;
948 return 0;