Update.
[glibc.git] / argp / argp-parse.c
blob02dbfac75da1ec2b82bbd30620ef3ea92ce2da97
1 /* Hierarchial argument parsing, layered over getopt
2 Copyright (C) 1995, 96, 97, 98, 99, 2000 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Written by Miles Bader <miles@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 #ifdef HAVE_CONFIG_H
22 #include <config.h>
23 #endif
25 #include <stdlib.h>
26 #include <string.h>
27 #include <unistd.h>
28 #include <limits.h>
29 #include <getopt.h>
31 #ifndef _
32 /* This is for other GNU distributions with internationalized messages.
33 When compiling libc, the _ macro is predefined. */
34 # if defined HAVE_LIBINTL_H || defined _LIBC
35 # include <libintl.h>
36 # ifdef _LIBC
37 # undef dgettext
38 # define dgettext(domain, msgid) __dcgettext (domain, msgid, LC_MESSAGES)
39 # endif
40 # else
41 # define dgettext(domain, msgid) (msgid)
42 # define gettext(msgid) (msgid)
43 # endif
44 #endif
45 #ifndef N_
46 # define N_(msgid) (msgid)
47 #endif
49 #if _LIBC - 0
50 #include <bits/libc-lock.h>
51 #else
52 #ifdef HAVE_CTHREADS_H
53 #include <cthreads.h>
54 #endif
55 #endif /* _LIBC */
57 #include "argp.h"
58 #include "argp-namefrob.h"
60 /* Getopt return values. */
61 #define KEY_END (-1) /* The end of the options. */
62 #define KEY_ARG 1 /* A non-option argument. */
63 #define KEY_ERR '?' /* An error parsing the options. */
65 /* The meta-argument used to prevent any further arguments being interpreted
66 as options. */
67 #define QUOTE "--"
69 /* The number of bits we steal in a long-option value for our own use. */
70 #define GROUP_BITS CHAR_BIT
72 /* The number of bits available for the user value. */
73 #define USER_BITS ((sizeof ((struct option *)0)->val * CHAR_BIT) - GROUP_BITS)
74 #define USER_MASK ((1 << USER_BITS) - 1)
76 /* EZ alias for ARGP_ERR_UNKNOWN. */
77 #define EBADKEY ARGP_ERR_UNKNOWN
79 /* Default options. */
81 /* When argp is given the --HANG switch, _ARGP_HANG is set and argp will sleep
82 for one second intervals, decrementing _ARGP_HANG until it's zero. Thus
83 you can force the program to continue by attaching a debugger and setting
84 it to 0 yourself. */
85 volatile int _argp_hang;
87 #define OPT_PROGNAME -2
88 #define OPT_USAGE -3
89 #define OPT_HANG -4
91 static const struct argp_option argp_default_options[] =
93 {"help", '?', 0, 0, N_("Give this help list"), -1},
94 {"usage", OPT_USAGE, 0, 0, N_("Give a short usage message")},
95 {"program-name",OPT_PROGNAME,"NAME", OPTION_HIDDEN, N_("Set the program name")},
96 {"HANG", OPT_HANG, "SECS", OPTION_ARG_OPTIONAL | OPTION_HIDDEN,
97 N_("Hang for SECS seconds (default 3600)")},
98 {0, 0}
101 static error_t
102 argp_default_parser (int key, char *arg, struct argp_state *state)
104 switch (key)
106 case '?':
107 __argp_state_help (state, state->out_stream, ARGP_HELP_STD_HELP);
108 break;
109 case OPT_USAGE:
110 __argp_state_help (state, state->out_stream,
111 ARGP_HELP_USAGE | ARGP_HELP_EXIT_OK);
112 break;
114 case OPT_PROGNAME: /* Set the program name. */
115 program_invocation_name = arg;
117 /* [Note that some systems only have PROGRAM_INVOCATION_SHORT_NAME (aka
118 __PROGNAME), in which case, PROGRAM_INVOCATION_NAME is just defined
119 to be that, so we have to be a bit careful here.] */
120 arg = strrchr (arg, '/');
121 if (arg)
122 program_invocation_short_name = arg + 1;
123 else
124 program_invocation_short_name = program_invocation_name;
126 /* Update what we use for messages. */
127 state->name = program_invocation_short_name;
129 if ((state->flags & (ARGP_PARSE_ARGV0 | ARGP_NO_ERRS))
130 == ARGP_PARSE_ARGV0)
131 /* Update what getopt uses too. */
132 state->argv[0] = program_invocation_name;
134 break;
136 case OPT_HANG:
137 _argp_hang = atoi (arg ? arg : "3600");
138 while (_argp_hang-- > 0)
139 __sleep (1);
140 break;
142 default:
143 return EBADKEY;
145 return 0;
148 static const struct argp argp_default_argp =
149 {argp_default_options, &argp_default_parser, NULL, NULL, NULL, NULL, "libc"};
152 static const struct argp_option argp_version_options[] =
154 {"version", 'V', 0, 0, N_("Print program version"), -1},
155 {0, 0}
158 static error_t
159 argp_version_parser (int key, char *arg, struct argp_state *state)
161 switch (key)
163 case 'V':
164 if (argp_program_version_hook)
165 (*argp_program_version_hook) (state->out_stream, state);
166 else if (argp_program_version)
167 fprintf (state->out_stream, "%s\n", argp_program_version);
168 else
169 __argp_error (state, dgettext (state->root_argp->argp_domain,
170 "(PROGRAM ERROR) No version known!?"));
171 if (! (state->flags & ARGP_NO_EXIT))
172 exit (0);
173 break;
174 default:
175 return EBADKEY;
177 return 0;
180 static const struct argp argp_version_argp =
181 {argp_version_options, &argp_version_parser, NULL, NULL, NULL, NULL, "libc"};
183 /* Returns the offset into the getopt long options array LONG_OPTIONS of a
184 long option with called NAME, or -1 if none is found. Passing NULL as
185 NAME will return the number of options. */
186 static int
187 find_long_option (struct option *long_options, const char *name)
189 struct option *l = long_options;
190 while (l->name != NULL)
191 if (name != NULL && strcmp (l->name, name) == 0)
192 return l - long_options;
193 else
194 l++;
195 if (name == NULL)
196 return l - long_options;
197 else
198 return -1;
201 /* If we can, we regulate access to getopt, which is non-reentrant, with a
202 mutex. Since the case we're trying to guard against is two different
203 threads interfering, and it's possible that someone might want to call
204 argp_parse recursively (they're careful), we use a recursive lock if
205 possible. */
207 #if _LIBC - 0
209 __libc_lock_define_initialized_recursive (static, getopt_lock)
210 #define LOCK_GETOPT __libc_lock_lock_recursive (getopt_lock)
211 #define UNLOCK_GETOPT __libc_lock_unlock_recursive (getopt_lock)
213 #else /* !_LIBC */
214 #ifdef HAVE_CTHREADS_H
216 static struct mutex getopt_lock = MUTEX_INITIALIZER;
217 #define LOCK_GETOPT mutex_lock (&getopt_lock)
218 #define UNLOCK_GETOPT mutex_unlock (&getopt_lock)
220 #else /* !HAVE_CTHREADS_H */
222 #define LOCK_GETOPT (void)0
223 #define UNLOCK_GETOPT (void)0
225 #endif /* HAVE_CTHREADS_H */
226 #endif /* _LIBC */
228 /* This hack to allow programs that know what's going on to call argp
229 recursively. If someday argp is changed not to use the non-reentrant
230 getopt interface, we can get rid of this shit. XXX */
231 void
232 _argp_unlock_xxx (void)
234 UNLOCK_GETOPT;
237 /* The state of a `group' during parsing. Each group corresponds to a
238 particular argp structure from the tree of such descending from the top
239 level argp passed to argp_parse. */
240 struct group
242 /* This group's parsing function. */
243 argp_parser_t parser;
245 /* Which argp this group is from. */
246 const struct argp *argp;
248 /* Points to the point in SHORT_OPTS corresponding to the end of the short
249 options for this group. We use it to determine from which group a
250 particular short options is from. */
251 char *short_end;
253 /* The number of non-option args sucessfully handled by this parser. */
254 unsigned args_processed;
256 /* This group's parser's parent's group. */
257 struct group *parent;
258 unsigned parent_index; /* And the our position in the parent. */
260 /* These fields are swapped into and out of the state structure when
261 calling this group's parser. */
262 void *input, **child_inputs;
263 void *hook;
266 /* Call GROUP's parser with KEY and ARG, swapping any group-specific info
267 from STATE before calling, and back into state afterwards. If GROUP has
268 no parser, EBADKEY is returned. */
269 static error_t
270 group_parse (struct group *group, struct argp_state *state, int key, char *arg)
272 if (group->parser)
274 error_t err;
275 state->hook = group->hook;
276 state->input = group->input;
277 state->child_inputs = group->child_inputs;
278 state->arg_num = group->args_processed;
279 err = (*group->parser)(key, arg, state);
280 group->hook = state->hook;
281 return err;
283 else
284 return EBADKEY;
287 struct parser
289 const struct argp *argp;
291 /* SHORT_OPTS is the getopt short options string for the union of all the
292 groups of options. */
293 char *short_opts;
294 /* LONG_OPTS is the array of getop long option structures for the union of
295 all the groups of options. */
296 struct option *long_opts;
298 /* States of the various parsing groups. */
299 struct group *groups;
300 /* The end of the GROUPS array. */
301 struct group *egroup;
302 /* An vector containing storage for the CHILD_INPUTS field in all groups. */
303 void **child_inputs;
305 /* True if we think using getopt is still useful; if false, then
306 remaining arguments are just passed verbatim with ARGP_KEY_ARG. This is
307 cleared whenever getopt returns KEY_END, but may be set again if the user
308 moves the next argument pointer backwards. */
309 int try_getopt;
311 /* State block supplied to parsing routines. */
312 struct argp_state state;
314 /* Memory used by this parser. */
315 void *storage;
318 /* The next usable entries in the various parser tables being filled in by
319 convert_options. */
320 struct parser_convert_state
322 struct parser *parser;
323 char *short_end;
324 struct option *long_end;
325 void **child_inputs_end;
328 /* Converts all options in ARGP (which is put in GROUP) and ancestors
329 into getopt options stored in SHORT_OPTS and LONG_OPTS; SHORT_END and
330 CVT->LONG_END are the points at which new options are added. Returns the
331 next unused group entry. CVT holds state used during the conversion. */
332 static struct group *
333 convert_options (const struct argp *argp,
334 struct group *parent, unsigned parent_index,
335 struct group *group, struct parser_convert_state *cvt)
337 /* REAL is the most recent non-alias value of OPT. */
338 const struct argp_option *real = argp->options;
339 const struct argp_child *children = argp->children;
341 if (real || argp->parser)
343 const struct argp_option *opt;
345 if (real)
346 for (opt = real; !__option_is_end (opt); opt++)
348 if (! (opt->flags & OPTION_ALIAS))
349 /* OPT isn't an alias, so we can use values from it. */
350 real = opt;
352 if (! (real->flags & OPTION_DOC))
353 /* A real option (not just documentation). */
355 if (__option_is_short (opt))
356 /* OPT can be used as a short option. */
358 *cvt->short_end++ = opt->key;
359 if (real->arg)
361 *cvt->short_end++ = ':';
362 if (real->flags & OPTION_ARG_OPTIONAL)
363 *cvt->short_end++ = ':';
365 *cvt->short_end = '\0'; /* keep 0 terminated */
368 if (opt->name
369 && find_long_option (cvt->parser->long_opts, opt->name) < 0)
370 /* OPT can be used as a long option. */
372 cvt->long_end->name = opt->name;
373 cvt->long_end->has_arg =
374 (real->arg
375 ? (real->flags & OPTION_ARG_OPTIONAL
376 ? optional_argument
377 : required_argument)
378 : no_argument);
379 cvt->long_end->flag = 0;
380 /* we add a disambiguating code to all the user's
381 values (which is removed before we actually call
382 the function to parse the value); this means that
383 the user loses use of the high 8 bits in all his
384 values (the sign of the lower bits is preserved
385 however)... */
386 cvt->long_end->val =
387 ((opt->key | real->key) & USER_MASK)
388 + (((group - cvt->parser->groups) + 1) << USER_BITS);
390 /* Keep the LONG_OPTS list terminated. */
391 (++cvt->long_end)->name = NULL;
396 group->parser = argp->parser;
397 group->argp = argp;
398 group->short_end = cvt->short_end;
399 group->args_processed = 0;
400 group->parent = parent;
401 group->parent_index = parent_index;
402 group->input = 0;
403 group->hook = 0;
404 group->child_inputs = 0;
406 if (children)
407 /* Assign GROUP's CHILD_INPUTS field some space from
408 CVT->child_inputs_end.*/
410 unsigned num_children = 0;
411 while (children[num_children].argp)
412 num_children++;
413 group->child_inputs = cvt->child_inputs_end;
414 cvt->child_inputs_end += num_children;
417 parent = group++;
419 else
420 parent = 0;
422 if (children)
424 unsigned index = 0;
425 while (children->argp)
426 group =
427 convert_options (children++->argp, parent, index++, group, cvt);
430 return group;
433 /* Find the merged set of getopt options, with keys appropiately prefixed. */
434 static void
435 parser_convert (struct parser *parser, const struct argp *argp, int flags)
437 struct parser_convert_state cvt;
439 cvt.parser = parser;
440 cvt.short_end = parser->short_opts;
441 cvt.long_end = parser->long_opts;
442 cvt.child_inputs_end = parser->child_inputs;
444 if (flags & ARGP_IN_ORDER)
445 *cvt.short_end++ = '-';
446 else if (flags & ARGP_NO_ARGS)
447 *cvt.short_end++ = '+';
448 *cvt.short_end = '\0';
450 cvt.long_end->name = NULL;
452 parser->argp = argp;
454 if (argp)
455 parser->egroup = convert_options (argp, 0, 0, parser->groups, &cvt);
456 else
457 parser->egroup = parser->groups; /* No parsers at all! */
460 /* Lengths of various parser fields which we will allocated. */
461 struct parser_sizes
463 size_t short_len; /* Getopt short options string. */
464 size_t long_len; /* Getopt long options vector. */
465 size_t num_groups; /* Group structures we allocate. */
466 size_t num_child_inputs; /* Child input slots. */
469 /* For ARGP, increments the NUM_GROUPS field in SZS by the total number of
470 argp structures descended from it, and the SHORT_LEN & LONG_LEN fields by
471 the maximum lengths of the resulting merged getopt short options string and
472 long-options array, respectively. */
473 static void
474 calc_sizes (const struct argp *argp, struct parser_sizes *szs)
476 const struct argp_child *child = argp->children;
477 const struct argp_option *opt = argp->options;
479 if (opt || argp->parser)
481 szs->num_groups++;
482 if (opt)
484 int num_opts = 0;
485 while (!__option_is_end (opt++))
486 num_opts++;
487 szs->short_len += num_opts * 3; /* opt + up to 2 `:'s */
488 szs->long_len += num_opts;
492 if (child)
493 while (child->argp)
495 calc_sizes ((child++)->argp, szs);
496 szs->num_child_inputs++;
500 /* Initializes PARSER to parse ARGP in a manner described by FLAGS. */
501 static error_t
502 parser_init (struct parser *parser, const struct argp *argp,
503 int argc, char **argv, int flags, void *input)
505 error_t err = 0;
506 struct group *group;
507 struct parser_sizes szs;
509 szs.short_len = (flags & ARGP_NO_ARGS) ? 0 : 1;
510 szs.long_len = 0;
511 szs.num_groups = 0;
512 szs.num_child_inputs = 0;
514 if (argp)
515 calc_sizes (argp, &szs);
517 /* Lengths of the various bits of storage used by PARSER. */
518 #define GLEN (szs.num_groups + 1) * sizeof (struct group)
519 #define CLEN (szs.num_child_inputs * sizeof (void *))
520 #define LLEN ((szs.long_len + 1) * sizeof (struct option))
521 #define SLEN (szs.short_len + 1)
523 parser->storage = malloc (GLEN + CLEN + LLEN + SLEN);
524 if (! parser->storage)
525 return ENOMEM;
527 parser->groups = parser->storage;
528 parser->child_inputs = parser->storage + GLEN;
529 parser->long_opts = parser->storage + GLEN + CLEN;
530 parser->short_opts = parser->storage + GLEN + CLEN + LLEN;
532 memset (parser->child_inputs, 0, szs.num_child_inputs * sizeof (void *));
533 parser_convert (parser, argp, flags);
535 memset (&parser->state, 0, sizeof (struct argp_state));
536 parser->state.root_argp = parser->argp;
537 parser->state.argc = argc;
538 parser->state.argv = argv;
539 parser->state.flags = flags;
540 parser->state.err_stream = stderr;
541 parser->state.out_stream = stdout;
542 parser->state.next = 0; /* Tell getopt to initialize. */
543 parser->state.pstate = parser;
545 parser->try_getopt = 1;
547 /* Call each parser for the first time, giving it a chance to propagate
548 values to child parsers. */
549 if (parser->groups < parser->egroup)
550 parser->groups->input = input;
551 for (group = parser->groups;
552 group < parser->egroup && (!err || err == EBADKEY);
553 group++)
555 if (group->parent)
556 /* If a child parser, get the initial input value from the parent. */
557 group->input = group->parent->child_inputs[group->parent_index];
559 if (!group->parser
560 && group->argp->children && group->argp->children->argp)
561 /* For the special case where no parsing function is supplied for an
562 argp, propagate its input to its first child, if any (this just
563 makes very simple wrapper argps more convenient). */
564 group->child_inputs[0] = group->input;
566 err = group_parse (group, &parser->state, ARGP_KEY_INIT, 0);
568 if (err == EBADKEY)
569 err = 0; /* Some parser didn't understand. */
571 if (err)
572 return err;
574 /* Getopt is (currently) non-reentrant. */
575 LOCK_GETOPT;
577 if (parser->state.flags & ARGP_NO_ERRS)
579 opterr = 0;
580 if (parser->state.flags & ARGP_PARSE_ARGV0)
581 /* getopt always skips ARGV[0], so we have to fake it out. As long
582 as OPTERR is 0, then it shouldn't actually try to access it. */
583 parser->state.argv--, parser->state.argc++;
585 else
586 opterr = 1; /* Print error messages. */
588 if (parser->state.argv == argv && argv[0])
589 /* There's an argv[0]; use it for messages. */
591 char *short_name = strrchr (argv[0], '/');
592 parser->state.name = short_name ? short_name + 1 : argv[0];
594 else
595 parser->state.name = program_invocation_short_name;
597 return 0;
600 /* Free any storage consumed by PARSER (but not PARSER itself). */
601 static error_t
602 parser_finalize (struct parser *parser,
603 error_t err, int arg_ebadkey, int *end_index)
605 struct group *group;
607 UNLOCK_GETOPT;
609 if (err == EBADKEY && arg_ebadkey)
610 /* Suppress errors generated by unparsed arguments. */
611 err = 0;
613 if (! err)
615 if (parser->state.next == parser->state.argc)
616 /* We successfully parsed all arguments! Call all the parsers again,
617 just a few more times... */
619 for (group = parser->groups;
620 group < parser->egroup && (!err || err==EBADKEY);
621 group++)
622 if (group->args_processed == 0)
623 err = group_parse (group, &parser->state, ARGP_KEY_NO_ARGS, 0);
624 for (group = parser->egroup - 1;
625 group >= parser->groups && (!err || err==EBADKEY);
626 group--)
627 err = group_parse (group, &parser->state, ARGP_KEY_END, 0);
629 if (err == EBADKEY)
630 err = 0; /* Some parser didn't understand. */
632 /* Tell the user that all arguments are parsed. */
633 if (end_index)
634 *end_index = parser->state.next;
636 else if (end_index)
637 /* Return any remaining arguments to the user. */
638 *end_index = parser->state.next;
639 else
640 /* No way to return the remaining arguments, they must be bogus. */
642 if (!(parser->state.flags & ARGP_NO_ERRS)
643 && parser->state.err_stream)
644 fprintf (parser->state.err_stream,
645 dgettext (parser->argp->argp_domain,
646 "%s: Too many arguments\n"),
647 parser->state.name);
648 err = EBADKEY;
652 /* Okay, we're all done, with either an error or success; call the parsers
653 to indicate which one. */
655 if (err)
657 /* Maybe print an error message. */
658 if (err == EBADKEY)
659 /* An appropriate message describing what the error was should have
660 been printed earlier. */
661 __argp_state_help (&parser->state, parser->state.err_stream,
662 ARGP_HELP_STD_ERR);
664 /* Since we didn't exit, give each parser an error indication. */
665 for (group = parser->groups; group < parser->egroup; group++)
666 group_parse (group, &parser->state, ARGP_KEY_ERROR, 0);
668 else
669 /* Notify parsers of success, and propagate back values from parsers. */
671 /* We pass over the groups in reverse order so that child groups are
672 given a chance to do there processing before passing back a value to
673 the parent. */
674 for (group = parser->egroup - 1
675 ; group >= parser->groups && (!err || err == EBADKEY)
676 ; group--)
677 err = group_parse (group, &parser->state, ARGP_KEY_SUCCESS, 0);
678 if (err == EBADKEY)
679 err = 0; /* Some parser didn't understand. */
682 /* Call parsers once more, to do any final cleanup. Errors are ignored. */
683 for (group = parser->egroup - 1; group >= parser->groups; group--)
684 group_parse (group, &parser->state, ARGP_KEY_FINI, 0);
686 if (err == EBADKEY)
687 err = EINVAL;
689 free (parser->storage);
691 return err;
694 /* Call the user parsers to parse the non-option argument VAL, at the current
695 position, returning any error. The state NEXT pointer is assumed to have
696 been adjusted (by getopt) to point after this argument; this function will
697 adjust it correctly to reflect however many args actually end up being
698 consumed. */
699 static error_t
700 parser_parse_arg (struct parser *parser, char *val)
702 /* Save the starting value of NEXT, first adjusting it so that the arg
703 we're parsing is again the front of the arg vector. */
704 int index = --parser->state.next;
705 error_t err = EBADKEY;
706 struct group *group;
707 int key = 0; /* Which of ARGP_KEY_ARG[S] we used. */
709 /* Try to parse the argument in each parser. */
710 for (group = parser->groups
711 ; group < parser->egroup && err == EBADKEY
712 ; group++)
714 parser->state.next++; /* For ARGP_KEY_ARG, consume the arg. */
715 key = ARGP_KEY_ARG;
716 err = group_parse (group, &parser->state, key, val);
718 if (err == EBADKEY)
719 /* This parser doesn't like ARGP_KEY_ARG; try ARGP_KEY_ARGS instead. */
721 parser->state.next--; /* For ARGP_KEY_ARGS, put back the arg. */
722 key = ARGP_KEY_ARGS;
723 err = group_parse (group, &parser->state, key, 0);
727 if (! err)
729 if (key == ARGP_KEY_ARGS)
730 /* The default for ARGP_KEY_ARGS is to assume that if NEXT isn't
731 changed by the user, *all* arguments should be considered
732 consumed. */
733 parser->state.next = parser->state.argc;
735 if (parser->state.next > index)
736 /* Remember that we successfully processed a non-option
737 argument -- but only if the user hasn't gotten tricky and set
738 the clock back. */
739 (--group)->args_processed += (parser->state.next - index);
740 else
741 /* The user wants to reparse some args, give getopt another try. */
742 parser->try_getopt = 1;
745 return err;
748 /* Call the user parsers to parse the option OPT, with argument VAL, at the
749 current position, returning any error. */
750 static error_t
751 parser_parse_opt (struct parser *parser, int opt, char *val)
753 /* The group key encoded in the high bits; 0 for short opts or
754 group_number + 1 for long opts. */
755 int group_key = opt >> USER_BITS;
756 error_t err = EBADKEY;
758 if (group_key == 0)
759 /* A short option. By comparing OPT's position in SHORT_OPTS to the
760 various starting positions in each group's SHORT_END field, we can
761 determine which group OPT came from. */
763 struct group *group;
764 char *short_index = strchr (parser->short_opts, opt);
766 if (short_index)
767 for (group = parser->groups; group < parser->egroup; group++)
768 if (group->short_end > short_index)
770 err = group_parse (group, &parser->state, opt, optarg);
771 break;
774 else
775 /* A long option. We use shifts instead of masking for extracting
776 the user value in order to preserve the sign. */
777 err =
778 group_parse (&parser->groups[group_key - 1], &parser->state,
779 (opt << GROUP_BITS) >> GROUP_BITS, optarg);
781 if (err == EBADKEY)
782 /* At least currently, an option not recognized is an error in the
783 parser, because we pre-compute which parser is supposed to deal
784 with each option. */
786 static const char bad_key_err[] =
787 N_("(PROGRAM ERROR) Option should have been recognized!?");
788 if (group_key == 0)
789 __argp_error (&parser->state, "-%c: %s", opt,
790 dgettext (parser->argp->argp_domain, bad_key_err));
791 else
793 struct option *long_opt = parser->long_opts;
794 while (long_opt->val != opt && long_opt->name)
795 long_opt++;
796 __argp_error (&parser->state, "--%s: %s",
797 long_opt->name ? long_opt->name : "???",
798 dgettext (parser->argp->argp_domain, bad_key_err));
802 return err;
805 /* Parse the next argument in PARSER (as indicated by PARSER->state.next).
806 Any error from the parsers is returned, and *ARGP_EBADKEY indicates
807 whether a value of EBADKEY is due to an unrecognized argument (which is
808 generally not fatal). */
809 static error_t
810 parser_parse_next (struct parser *parser, int *arg_ebadkey)
812 int opt;
813 error_t err = 0;
815 if (parser->state.quoted && parser->state.next < parser->state.quoted)
816 /* The next argument pointer has been moved to before the quoted
817 region, so pretend we never saw the quoting `--', and give getopt
818 another chance. If the user hasn't removed it, getopt will just
819 process it again. */
820 parser->state.quoted = 0;
822 if (parser->try_getopt && !parser->state.quoted)
823 /* Give getopt a chance to parse this. */
825 optind = parser->state.next; /* Put it back in OPTIND for getopt. */
826 optopt = KEY_END; /* Distinguish KEY_ERR from a real option. */
827 if (parser->state.flags & ARGP_LONG_ONLY)
828 opt = getopt_long_only (parser->state.argc, parser->state.argv,
829 parser->short_opts, parser->long_opts, 0);
830 else
831 opt = getopt_long (parser->state.argc, parser->state.argv,
832 parser->short_opts, parser->long_opts, 0);
833 parser->state.next = optind; /* And see what getopt did. */
835 if (opt == KEY_END)
836 /* Getopt says there are no more options, so stop using
837 getopt; we'll continue if necessary on our own. */
839 parser->try_getopt = 0;
840 if (parser->state.next > 1
841 && strcmp (parser->state.argv[parser->state.next - 1], QUOTE)
842 == 0)
843 /* Not only is this the end of the options, but it's a
844 `quoted' region, which may have args that *look* like
845 options, so we definitely shouldn't try to use getopt past
846 here, whatever happens. */
847 parser->state.quoted = parser->state.next;
849 else if (opt == KEY_ERR && optopt != KEY_END)
850 /* KEY_ERR can have the same value as a valid user short
851 option, but in the case of a real error, getopt sets OPTOPT
852 to the offending character, which can never be KEY_END. */
854 *arg_ebadkey = 0;
855 return EBADKEY;
858 else
859 opt = KEY_END;
861 if (opt == KEY_END)
863 /* We're past what getopt considers the options. */
864 if (parser->state.next >= parser->state.argc
865 || (parser->state.flags & ARGP_NO_ARGS))
866 /* Indicate that we're done. */
868 *arg_ebadkey = 1;
869 return EBADKEY;
871 else
872 /* A non-option arg; simulate what getopt might have done. */
874 opt = KEY_ARG;
875 optarg = parser->state.argv[parser->state.next++];
879 if (opt == KEY_ARG)
880 /* A non-option argument; try each parser in turn. */
881 err = parser_parse_arg (parser, optarg);
882 else
883 err = parser_parse_opt (parser, opt, optarg);
885 if (err == EBADKEY)
886 *arg_ebadkey = (opt == KEY_END || opt == KEY_ARG);
888 return err;
891 /* Parse the options strings in ARGC & ARGV according to the argp in ARGP.
892 FLAGS is one of the ARGP_ flags above. If END_INDEX is non-NULL, the
893 index in ARGV of the first unparsed option is returned in it. If an
894 unknown option is present, EINVAL is returned; if some parser routine
895 returned a non-zero value, it is returned; otherwise 0 is returned. */
896 error_t
897 __argp_parse (const struct argp *argp, int argc, char **argv, unsigned flags,
898 int *end_index, void *input)
900 error_t err;
901 struct parser parser;
903 /* If true, then err == EBADKEY is a result of a non-option argument failing
904 to be parsed (which in some cases isn't actually an error). */
905 int arg_ebadkey = 0;
907 if (! (flags & ARGP_NO_HELP))
908 /* Add our own options. */
910 struct argp_child *child = alloca (4 * sizeof (struct argp_child));
911 struct argp *top_argp = alloca (sizeof (struct argp));
913 /* TOP_ARGP has no options, it just serves to group the user & default
914 argps. */
915 memset (top_argp, 0, sizeof (*top_argp));
916 top_argp->children = child;
918 memset (child, 0, 4 * sizeof (struct argp_child));
920 if (argp)
921 (child++)->argp = argp;
922 (child++)->argp = &argp_default_argp;
923 if (argp_program_version || argp_program_version_hook)
924 (child++)->argp = &argp_version_argp;
925 child->argp = 0;
927 argp = top_argp;
930 /* Construct a parser for these arguments. */
931 err = parser_init (&parser, argp, argc, argv, flags, input);
933 if (! err)
934 /* Parse! */
936 while (! err)
937 err = parser_parse_next (&parser, &arg_ebadkey);
938 err = parser_finalize (&parser, err, arg_ebadkey, end_index);
941 return err;
943 #ifdef weak_alias
944 weak_alias (__argp_parse, argp_parse)
945 #endif
947 /* Return the input field for ARGP in the parser corresponding to STATE; used
948 by the help routines. */
949 void *
950 __argp_input (const struct argp *argp, const struct argp_state *state)
952 if (state)
954 struct group *group;
955 struct parser *parser = state->pstate;
957 for (group = parser->groups; group < parser->egroup; group++)
958 if (group->argp == argp)
959 return group->input;
962 return 0;
964 #ifdef weak_alias
965 weak_alias (__argp_input, _argp_input)
966 #endif