Version 0.0.3.
[shishi.git] / gl / argp-parse.c
blob0b619db0f305db91a39ea37f8c1d8e1d43488cff
1 /* Hierarchial argument parsing, layered over getopt
2 Copyright (C) 1995-2000, 2002 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) \
39 INTUSE(__dcgettext) (domain, msgid, LC_MESSAGES)
40 # endif
41 # else
42 # define dgettext(domain, msgid) (msgid)
43 # define gettext(msgid) (msgid)
44 # endif
45 #endif
46 #ifndef N_
47 # define N_(msgid) (msgid)
48 #endif
50 #if _LIBC - 0
51 #include <bits/libc-lock.h>
52 #else
53 #ifdef HAVE_CTHREADS_H
54 #include <cthreads.h>
55 #endif
56 #endif /* _LIBC */
58 #include "argp.h"
59 #include "argp-namefrob.h"
61 /* Getopt return values. */
62 #define KEY_END (-1) /* The end of the options. */
63 #define KEY_ARG 1 /* A non-option argument. */
64 #define KEY_ERR '?' /* An error parsing the options. */
66 /* The meta-argument used to prevent any further arguments being interpreted
67 as options. */
68 #define QUOTE "--"
70 /* The number of bits we steal in a long-option value for our own use. */
71 #define GROUP_BITS CHAR_BIT
73 /* The number of bits available for the user value. */
74 #define USER_BITS ((sizeof ((struct option *)0)->val * CHAR_BIT) - GROUP_BITS)
75 #define USER_MASK ((1 << USER_BITS) - 1)
77 /* EZ alias for ARGP_ERR_UNKNOWN. */
78 #define EBADKEY ARGP_ERR_UNKNOWN
80 /* Default options. */
82 /* When argp is given the --HANG switch, _ARGP_HANG is set and argp will sleep
83 for one second intervals, decrementing _ARGP_HANG until it's zero. Thus
84 you can force the program to continue by attaching a debugger and setting
85 it to 0 yourself.
87 XXX This variable used to be exported. But there seems to be no
88 need, at least not inside libc. */
89 #ifdef _LIBC
90 static
91 #endif
92 volatile int _argp_hang;
94 #define OPT_PROGNAME -2
95 #define OPT_USAGE -3
96 #define OPT_HANG -4
98 static const struct argp_option argp_default_options[] =
100 {"help", '?', 0, 0, N_("Give this help list"), -1},
101 {"usage", OPT_USAGE, 0, 0, N_("Give a short usage message")},
102 {"program-name",OPT_PROGNAME,"NAME", OPTION_HIDDEN, N_("Set the program name")},
103 {"HANG", OPT_HANG, "SECS", OPTION_ARG_OPTIONAL | OPTION_HIDDEN,
104 N_("Hang for SECS seconds (default 3600)")},
105 {0, 0}
108 static error_t
109 argp_default_parser (int key, char *arg, struct argp_state *state)
111 switch (key)
113 case '?':
114 __argp_state_help (state, state->out_stream, ARGP_HELP_STD_HELP);
115 break;
116 case OPT_USAGE:
117 __argp_state_help (state, state->out_stream,
118 ARGP_HELP_USAGE | ARGP_HELP_EXIT_OK);
119 break;
121 case OPT_PROGNAME: /* Set the program name. */
122 #if defined _LIBC || HAVE_DECL_PROGRAM_INVOCATION_NAME
123 program_invocation_name = arg;
124 #endif
125 /* [Note that some systems only have PROGRAM_INVOCATION_SHORT_NAME (aka
126 __PROGNAME), in which case, PROGRAM_INVOCATION_NAME is just defined
127 to be that, so we have to be a bit careful here.] */
129 /* Update what we use for messages. */
130 state->name = strrchr (arg, '/');
131 if (state->name)
132 state->name++;
133 else
134 state->name = arg;
136 #if defined _LIBC || HAVE_DECL_PROGRAM_INVOCATION_SHORT_NAME
137 program_invocation_short_name = state->name;
138 #endif
140 if ((state->flags & (ARGP_PARSE_ARGV0 | ARGP_NO_ERRS))
141 == ARGP_PARSE_ARGV0)
142 /* Update what getopt uses too. */
143 state->argv[0] = arg;
145 break;
147 case OPT_HANG:
148 _argp_hang = atoi (arg ? arg : "3600");
149 while (_argp_hang-- > 0)
150 __sleep (1);
151 break;
153 default:
154 return EBADKEY;
156 return 0;
159 static const struct argp argp_default_argp =
160 {argp_default_options, &argp_default_parser, NULL, NULL, NULL, NULL, "libc"};
163 static const struct argp_option argp_version_options[] =
165 {"version", 'V', 0, 0, N_("Print program version"), -1},
166 {0, 0}
169 static error_t
170 argp_version_parser (int key, char *arg, struct argp_state *state)
172 switch (key)
174 case 'V':
175 if (argp_program_version_hook)
176 (*argp_program_version_hook) (state->out_stream, state);
177 else if (argp_program_version)
178 fprintf (state->out_stream, "%s\n", argp_program_version);
179 else
180 __argp_error (state, dgettext (state->root_argp->argp_domain,
181 "(PROGRAM ERROR) No version known!?"));
182 if (! (state->flags & ARGP_NO_EXIT))
183 exit (0);
184 break;
185 default:
186 return EBADKEY;
188 return 0;
191 static const struct argp argp_version_argp =
192 {argp_version_options, &argp_version_parser, NULL, NULL, NULL, NULL, "libc"};
194 /* Returns the offset into the getopt long options array LONG_OPTIONS of a
195 long option with called NAME, or -1 if none is found. Passing NULL as
196 NAME will return the number of options. */
197 static int
198 find_long_option (struct option *long_options, const char *name)
200 struct option *l = long_options;
201 while (l->name != NULL)
202 if (name != NULL && strcmp (l->name, name) == 0)
203 return l - long_options;
204 else
205 l++;
206 if (name == NULL)
207 return l - long_options;
208 else
209 return -1;
212 /* If we can, we regulate access to getopt, which is non-reentrant, with a
213 mutex. Since the case we're trying to guard against is two different
214 threads interfering, and it's possible that someone might want to call
215 argp_parse recursively (they're careful), we use a recursive lock if
216 possible. */
218 #if _LIBC - 0
220 __libc_lock_define_initialized_recursive (static, getopt_lock)
221 #define LOCK_GETOPT __libc_lock_lock_recursive (getopt_lock)
222 #define UNLOCK_GETOPT __libc_lock_unlock_recursive (getopt_lock)
224 #else /* !_LIBC */
225 #ifdef HAVE_CTHREADS_H
227 static struct mutex getopt_lock = MUTEX_INITIALIZER;
228 #define LOCK_GETOPT mutex_lock (&getopt_lock)
229 #define UNLOCK_GETOPT mutex_unlock (&getopt_lock)
231 #else /* !HAVE_CTHREADS_H */
233 #define LOCK_GETOPT (void)0
234 #define UNLOCK_GETOPT (void)0
236 #endif /* HAVE_CTHREADS_H */
237 #endif /* _LIBC */
239 /* This hack to allow programs that know what's going on to call argp
240 recursively. If someday argp is changed not to use the non-reentrant
241 getopt interface, we can get rid of this shit. XXX */
242 void
243 _argp_unlock_xxx (void)
245 UNLOCK_GETOPT;
248 /* The state of a `group' during parsing. Each group corresponds to a
249 particular argp structure from the tree of such descending from the top
250 level argp passed to argp_parse. */
251 struct group
253 /* This group's parsing function. */
254 argp_parser_t parser;
256 /* Which argp this group is from. */
257 const struct argp *argp;
259 /* Points to the point in SHORT_OPTS corresponding to the end of the short
260 options for this group. We use it to determine from which group a
261 particular short options is from. */
262 char *short_end;
264 /* The number of non-option args sucessfully handled by this parser. */
265 unsigned args_processed;
267 /* This group's parser's parent's group. */
268 struct group *parent;
269 unsigned parent_index; /* And the our position in the parent. */
271 /* These fields are swapped into and out of the state structure when
272 calling this group's parser. */
273 void *input, **child_inputs;
274 void *hook;
277 /* Call GROUP's parser with KEY and ARG, swapping any group-specific info
278 from STATE before calling, and back into state afterwards. If GROUP has
279 no parser, EBADKEY is returned. */
280 static error_t
281 group_parse (struct group *group, struct argp_state *state, int key, char *arg)
283 if (group->parser)
285 error_t err;
286 state->hook = group->hook;
287 state->input = group->input;
288 state->child_inputs = group->child_inputs;
289 state->arg_num = group->args_processed;
290 err = (*group->parser)(key, arg, state);
291 group->hook = state->hook;
292 return err;
294 else
295 return EBADKEY;
298 struct parser
300 const struct argp *argp;
302 /* SHORT_OPTS is the getopt short options string for the union of all the
303 groups of options. */
304 char *short_opts;
305 /* LONG_OPTS is the array of getop long option structures for the union of
306 all the groups of options. */
307 struct option *long_opts;
309 /* States of the various parsing groups. */
310 struct group *groups;
311 /* The end of the GROUPS array. */
312 struct group *egroup;
313 /* An vector containing storage for the CHILD_INPUTS field in all groups. */
314 void **child_inputs;
316 /* True if we think using getopt is still useful; if false, then
317 remaining arguments are just passed verbatim with ARGP_KEY_ARG. This is
318 cleared whenever getopt returns KEY_END, but may be set again if the user
319 moves the next argument pointer backwards. */
320 int try_getopt;
322 /* State block supplied to parsing routines. */
323 struct argp_state state;
325 /* Memory used by this parser. */
326 void *storage;
329 /* The next usable entries in the various parser tables being filled in by
330 convert_options. */
331 struct parser_convert_state
333 struct parser *parser;
334 char *short_end;
335 struct option *long_end;
336 void **child_inputs_end;
339 /* Converts all options in ARGP (which is put in GROUP) and ancestors
340 into getopt options stored in SHORT_OPTS and LONG_OPTS; SHORT_END and
341 CVT->LONG_END are the points at which new options are added. Returns the
342 next unused group entry. CVT holds state used during the conversion. */
343 static struct group *
344 convert_options (const struct argp *argp,
345 struct group *parent, unsigned parent_index,
346 struct group *group, struct parser_convert_state *cvt)
348 /* REAL is the most recent non-alias value of OPT. */
349 const struct argp_option *real = argp->options;
350 const struct argp_child *children = argp->children;
352 if (real || argp->parser)
354 const struct argp_option *opt;
356 if (real)
357 for (opt = real; !__option_is_end (opt); opt++)
359 if (! (opt->flags & OPTION_ALIAS))
360 /* OPT isn't an alias, so we can use values from it. */
361 real = opt;
363 if (! (real->flags & OPTION_DOC))
364 /* A real option (not just documentation). */
366 if (__option_is_short (opt))
367 /* OPT can be used as a short option. */
369 *cvt->short_end++ = opt->key;
370 if (real->arg)
372 *cvt->short_end++ = ':';
373 if (real->flags & OPTION_ARG_OPTIONAL)
374 *cvt->short_end++ = ':';
376 *cvt->short_end = '\0'; /* keep 0 terminated */
379 if (opt->name
380 && find_long_option (cvt->parser->long_opts, opt->name) < 0)
381 /* OPT can be used as a long option. */
383 cvt->long_end->name = opt->name;
384 cvt->long_end->has_arg =
385 (real->arg
386 ? (real->flags & OPTION_ARG_OPTIONAL
387 ? optional_argument
388 : required_argument)
389 : no_argument);
390 cvt->long_end->flag = 0;
391 /* we add a disambiguating code to all the user's
392 values (which is removed before we actually call
393 the function to parse the value); this means that
394 the user loses use of the high 8 bits in all his
395 values (the sign of the lower bits is preserved
396 however)... */
397 cvt->long_end->val =
398 ((opt->key | real->key) & USER_MASK)
399 + (((group - cvt->parser->groups) + 1) << USER_BITS);
401 /* Keep the LONG_OPTS list terminated. */
402 (++cvt->long_end)->name = NULL;
407 group->parser = argp->parser;
408 group->argp = argp;
409 group->short_end = cvt->short_end;
410 group->args_processed = 0;
411 group->parent = parent;
412 group->parent_index = parent_index;
413 group->input = 0;
414 group->hook = 0;
415 group->child_inputs = 0;
417 if (children)
418 /* Assign GROUP's CHILD_INPUTS field some space from
419 CVT->child_inputs_end.*/
421 unsigned num_children = 0;
422 while (children[num_children].argp)
423 num_children++;
424 group->child_inputs = cvt->child_inputs_end;
425 cvt->child_inputs_end += num_children;
428 parent = group++;
430 else
431 parent = 0;
433 if (children)
435 unsigned index = 0;
436 while (children->argp)
437 group =
438 convert_options (children++->argp, parent, index++, group, cvt);
441 return group;
444 /* Find the merged set of getopt options, with keys appropiately prefixed. */
445 static void
446 parser_convert (struct parser *parser, const struct argp *argp, int flags)
448 struct parser_convert_state cvt;
450 cvt.parser = parser;
451 cvt.short_end = parser->short_opts;
452 cvt.long_end = parser->long_opts;
453 cvt.child_inputs_end = parser->child_inputs;
455 if (flags & ARGP_IN_ORDER)
456 *cvt.short_end++ = '-';
457 else if (flags & ARGP_NO_ARGS)
458 *cvt.short_end++ = '+';
459 *cvt.short_end = '\0';
461 cvt.long_end->name = NULL;
463 parser->argp = argp;
465 if (argp)
466 parser->egroup = convert_options (argp, 0, 0, parser->groups, &cvt);
467 else
468 parser->egroup = parser->groups; /* No parsers at all! */
471 /* Lengths of various parser fields which we will allocated. */
472 struct parser_sizes
474 size_t short_len; /* Getopt short options string. */
475 size_t long_len; /* Getopt long options vector. */
476 size_t num_groups; /* Group structures we allocate. */
477 size_t num_child_inputs; /* Child input slots. */
480 /* For ARGP, increments the NUM_GROUPS field in SZS by the total number of
481 argp structures descended from it, and the SHORT_LEN & LONG_LEN fields by
482 the maximum lengths of the resulting merged getopt short options string and
483 long-options array, respectively. */
484 static void
485 calc_sizes (const struct argp *argp, struct parser_sizes *szs)
487 const struct argp_child *child = argp->children;
488 const struct argp_option *opt = argp->options;
490 if (opt || argp->parser)
492 szs->num_groups++;
493 if (opt)
495 int num_opts = 0;
496 while (!__option_is_end (opt++))
497 num_opts++;
498 szs->short_len += num_opts * 3; /* opt + up to 2 `:'s */
499 szs->long_len += num_opts;
503 if (child)
504 while (child->argp)
506 calc_sizes ((child++)->argp, szs);
507 szs->num_child_inputs++;
511 /* Initializes PARSER to parse ARGP in a manner described by FLAGS. */
512 static error_t
513 parser_init (struct parser *parser, const struct argp *argp,
514 int argc, char **argv, int flags, void *input)
516 error_t err = 0;
517 struct group *group;
518 struct parser_sizes szs;
520 szs.short_len = (flags & ARGP_NO_ARGS) ? 0 : 1;
521 szs.long_len = 0;
522 szs.num_groups = 0;
523 szs.num_child_inputs = 0;
525 if (argp)
526 calc_sizes (argp, &szs);
528 /* Lengths of the various bits of storage used by PARSER. */
529 #define GLEN (szs.num_groups + 1) * sizeof (struct group)
530 #define CLEN (szs.num_child_inputs * sizeof (void *))
531 #define LLEN ((szs.long_len + 1) * sizeof (struct option))
532 #define SLEN (szs.short_len + 1)
534 parser->storage = malloc (GLEN + CLEN + LLEN + SLEN);
535 if (! parser->storage)
536 return ENOMEM;
538 parser->groups = parser->storage;
539 parser->child_inputs = parser->storage + GLEN;
540 parser->long_opts = parser->storage + GLEN + CLEN;
541 parser->short_opts = parser->storage + GLEN + CLEN + LLEN;
543 memset (parser->child_inputs, 0, szs.num_child_inputs * sizeof (void *));
544 parser_convert (parser, argp, flags);
546 memset (&parser->state, 0, sizeof (struct argp_state));
547 parser->state.root_argp = parser->argp;
548 parser->state.argc = argc;
549 parser->state.argv = argv;
550 parser->state.flags = flags;
551 parser->state.err_stream = stderr;
552 parser->state.out_stream = stdout;
553 parser->state.next = 0; /* Tell getopt to initialize. */
554 parser->state.pstate = parser;
556 parser->try_getopt = 1;
558 /* Call each parser for the first time, giving it a chance to propagate
559 values to child parsers. */
560 if (parser->groups < parser->egroup)
561 parser->groups->input = input;
562 for (group = parser->groups;
563 group < parser->egroup && (!err || err == EBADKEY);
564 group++)
566 if (group->parent)
567 /* If a child parser, get the initial input value from the parent. */
568 group->input = group->parent->child_inputs[group->parent_index];
570 if (!group->parser
571 && group->argp->children && group->argp->children->argp)
572 /* For the special case where no parsing function is supplied for an
573 argp, propagate its input to its first child, if any (this just
574 makes very simple wrapper argps more convenient). */
575 group->child_inputs[0] = group->input;
577 err = group_parse (group, &parser->state, ARGP_KEY_INIT, 0);
579 if (err == EBADKEY)
580 err = 0; /* Some parser didn't understand. */
582 if (err)
583 return err;
585 /* Getopt is (currently) non-reentrant. */
586 LOCK_GETOPT;
588 if (parser->state.flags & ARGP_NO_ERRS)
590 opterr = 0;
591 if (parser->state.flags & ARGP_PARSE_ARGV0)
592 /* getopt always skips ARGV[0], so we have to fake it out. As long
593 as OPTERR is 0, then it shouldn't actually try to access it. */
594 parser->state.argv--, parser->state.argc++;
596 else
597 opterr = 1; /* Print error messages. */
599 if (parser->state.argv == argv && argv[0])
600 /* There's an argv[0]; use it for messages. */
602 char *short_name = strrchr (argv[0], '/');
603 parser->state.name = short_name ? short_name + 1 : argv[0];
605 else
606 parser->state.name = __argp_short_program_name ();
608 return 0;
611 /* Free any storage consumed by PARSER (but not PARSER itself). */
612 static error_t
613 parser_finalize (struct parser *parser,
614 error_t err, int arg_ebadkey, int *end_index)
616 struct group *group;
618 UNLOCK_GETOPT;
620 if (err == EBADKEY && arg_ebadkey)
621 /* Suppress errors generated by unparsed arguments. */
622 err = 0;
624 if (! err)
626 if (parser->state.next == parser->state.argc)
627 /* We successfully parsed all arguments! Call all the parsers again,
628 just a few more times... */
630 for (group = parser->groups;
631 group < parser->egroup && (!err || err==EBADKEY);
632 group++)
633 if (group->args_processed == 0)
634 err = group_parse (group, &parser->state, ARGP_KEY_NO_ARGS, 0);
635 for (group = parser->egroup - 1;
636 group >= parser->groups && (!err || err==EBADKEY);
637 group--)
638 err = group_parse (group, &parser->state, ARGP_KEY_END, 0);
640 if (err == EBADKEY)
641 err = 0; /* Some parser didn't understand. */
643 /* Tell the user that all arguments are parsed. */
644 if (end_index)
645 *end_index = parser->state.next;
647 else if (end_index)
648 /* Return any remaining arguments to the user. */
649 *end_index = parser->state.next;
650 else
651 /* No way to return the remaining arguments, they must be bogus. */
653 if (!(parser->state.flags & ARGP_NO_ERRS)
654 && parser->state.err_stream)
655 fprintf (parser->state.err_stream,
656 dgettext (parser->argp->argp_domain,
657 "%s: Too many arguments\n"),
658 parser->state.name);
659 err = EBADKEY;
663 /* Okay, we're all done, with either an error or success; call the parsers
664 to indicate which one. */
666 if (err)
668 /* Maybe print an error message. */
669 if (err == EBADKEY)
670 /* An appropriate message describing what the error was should have
671 been printed earlier. */
672 __argp_state_help (&parser->state, parser->state.err_stream,
673 ARGP_HELP_STD_ERR);
675 /* Since we didn't exit, give each parser an error indication. */
676 for (group = parser->groups; group < parser->egroup; group++)
677 group_parse (group, &parser->state, ARGP_KEY_ERROR, 0);
679 else
680 /* Notify parsers of success, and propagate back values from parsers. */
682 /* We pass over the groups in reverse order so that child groups are
683 given a chance to do there processing before passing back a value to
684 the parent. */
685 for (group = parser->egroup - 1
686 ; group >= parser->groups && (!err || err == EBADKEY)
687 ; group--)
688 err = group_parse (group, &parser->state, ARGP_KEY_SUCCESS, 0);
689 if (err == EBADKEY)
690 err = 0; /* Some parser didn't understand. */
693 /* Call parsers once more, to do any final cleanup. Errors are ignored. */
694 for (group = parser->egroup - 1; group >= parser->groups; group--)
695 group_parse (group, &parser->state, ARGP_KEY_FINI, 0);
697 if (err == EBADKEY)
698 err = EINVAL;
700 free (parser->storage);
702 return err;
705 /* Call the user parsers to parse the non-option argument VAL, at the current
706 position, returning any error. The state NEXT pointer is assumed to have
707 been adjusted (by getopt) to point after this argument; this function will
708 adjust it correctly to reflect however many args actually end up being
709 consumed. */
710 static error_t
711 parser_parse_arg (struct parser *parser, char *val)
713 /* Save the starting value of NEXT, first adjusting it so that the arg
714 we're parsing is again the front of the arg vector. */
715 int index = --parser->state.next;
716 error_t err = EBADKEY;
717 struct group *group;
718 int key = 0; /* Which of ARGP_KEY_ARG[S] we used. */
720 /* Try to parse the argument in each parser. */
721 for (group = parser->groups
722 ; group < parser->egroup && err == EBADKEY
723 ; group++)
725 parser->state.next++; /* For ARGP_KEY_ARG, consume the arg. */
726 key = ARGP_KEY_ARG;
727 err = group_parse (group, &parser->state, key, val);
729 if (err == EBADKEY)
730 /* This parser doesn't like ARGP_KEY_ARG; try ARGP_KEY_ARGS instead. */
732 parser->state.next--; /* For ARGP_KEY_ARGS, put back the arg. */
733 key = ARGP_KEY_ARGS;
734 err = group_parse (group, &parser->state, key, 0);
738 if (! err)
740 if (key == ARGP_KEY_ARGS)
741 /* The default for ARGP_KEY_ARGS is to assume that if NEXT isn't
742 changed by the user, *all* arguments should be considered
743 consumed. */
744 parser->state.next = parser->state.argc;
746 if (parser->state.next > index)
747 /* Remember that we successfully processed a non-option
748 argument -- but only if the user hasn't gotten tricky and set
749 the clock back. */
750 (--group)->args_processed += (parser->state.next - index);
751 else
752 /* The user wants to reparse some args, give getopt another try. */
753 parser->try_getopt = 1;
756 return err;
759 /* Call the user parsers to parse the option OPT, with argument VAL, at the
760 current position, returning any error. */
761 static error_t
762 parser_parse_opt (struct parser *parser, int opt, char *val)
764 /* The group key encoded in the high bits; 0 for short opts or
765 group_number + 1 for long opts. */
766 int group_key = opt >> USER_BITS;
767 error_t err = EBADKEY;
769 if (group_key == 0)
770 /* A short option. By comparing OPT's position in SHORT_OPTS to the
771 various starting positions in each group's SHORT_END field, we can
772 determine which group OPT came from. */
774 struct group *group;
775 char *short_index = strchr (parser->short_opts, opt);
777 if (short_index)
778 for (group = parser->groups; group < parser->egroup; group++)
779 if (group->short_end > short_index)
781 err = group_parse (group, &parser->state, opt, optarg);
782 break;
785 else
786 /* A long option. We use shifts instead of masking for extracting
787 the user value in order to preserve the sign. */
788 err =
789 group_parse (&parser->groups[group_key - 1], &parser->state,
790 (opt << GROUP_BITS) >> GROUP_BITS, optarg);
792 if (err == EBADKEY)
793 /* At least currently, an option not recognized is an error in the
794 parser, because we pre-compute which parser is supposed to deal
795 with each option. */
797 static const char bad_key_err[] =
798 N_("(PROGRAM ERROR) Option should have been recognized!?");
799 if (group_key == 0)
800 __argp_error (&parser->state, "-%c: %s", opt,
801 dgettext (parser->argp->argp_domain, bad_key_err));
802 else
804 struct option *long_opt = parser->long_opts;
805 while (long_opt->val != opt && long_opt->name)
806 long_opt++;
807 __argp_error (&parser->state, "--%s: %s",
808 long_opt->name ? long_opt->name : "???",
809 dgettext (parser->argp->argp_domain, bad_key_err));
813 return err;
816 /* Parse the next argument in PARSER (as indicated by PARSER->state.next).
817 Any error from the parsers is returned, and *ARGP_EBADKEY indicates
818 whether a value of EBADKEY is due to an unrecognized argument (which is
819 generally not fatal). */
820 static error_t
821 parser_parse_next (struct parser *parser, int *arg_ebadkey)
823 int opt;
824 error_t err = 0;
826 if (parser->state.quoted && parser->state.next < parser->state.quoted)
827 /* The next argument pointer has been moved to before the quoted
828 region, so pretend we never saw the quoting `--', and give getopt
829 another chance. If the user hasn't removed it, getopt will just
830 process it again. */
831 parser->state.quoted = 0;
833 if (parser->try_getopt && !parser->state.quoted)
834 /* Give getopt a chance to parse this. */
836 optind = parser->state.next; /* Put it back in OPTIND for getopt. */
837 optopt = KEY_END; /* Distinguish KEY_ERR from a real option. */
838 if (parser->state.flags & ARGP_LONG_ONLY)
839 opt = getopt_long_only (parser->state.argc, parser->state.argv,
840 parser->short_opts, parser->long_opts, 0);
841 else
842 opt = getopt_long (parser->state.argc, parser->state.argv,
843 parser->short_opts, parser->long_opts, 0);
844 parser->state.next = optind; /* And see what getopt did. */
846 if (opt == KEY_END)
847 /* Getopt says there are no more options, so stop using
848 getopt; we'll continue if necessary on our own. */
850 parser->try_getopt = 0;
851 if (parser->state.next > 1
852 && strcmp (parser->state.argv[parser->state.next - 1], QUOTE)
853 == 0)
854 /* Not only is this the end of the options, but it's a
855 `quoted' region, which may have args that *look* like
856 options, so we definitely shouldn't try to use getopt past
857 here, whatever happens. */
858 parser->state.quoted = parser->state.next;
860 else if (opt == KEY_ERR && optopt != KEY_END)
861 /* KEY_ERR can have the same value as a valid user short
862 option, but in the case of a real error, getopt sets OPTOPT
863 to the offending character, which can never be KEY_END. */
865 *arg_ebadkey = 0;
866 return EBADKEY;
869 else
870 opt = KEY_END;
872 if (opt == KEY_END)
874 /* We're past what getopt considers the options. */
875 if (parser->state.next >= parser->state.argc
876 || (parser->state.flags & ARGP_NO_ARGS))
877 /* Indicate that we're done. */
879 *arg_ebadkey = 1;
880 return EBADKEY;
882 else
883 /* A non-option arg; simulate what getopt might have done. */
885 opt = KEY_ARG;
886 optarg = parser->state.argv[parser->state.next++];
890 if (opt == KEY_ARG)
891 /* A non-option argument; try each parser in turn. */
892 err = parser_parse_arg (parser, optarg);
893 else
894 err = parser_parse_opt (parser, opt, optarg);
896 if (err == EBADKEY)
897 *arg_ebadkey = (opt == KEY_END || opt == KEY_ARG);
899 return err;
902 /* Parse the options strings in ARGC & ARGV according to the argp in ARGP.
903 FLAGS is one of the ARGP_ flags above. If END_INDEX is non-NULL, the
904 index in ARGV of the first unparsed option is returned in it. If an
905 unknown option is present, EINVAL is returned; if some parser routine
906 returned a non-zero value, it is returned; otherwise 0 is returned. */
907 error_t
908 __argp_parse (const struct argp *argp, int argc, char **argv, unsigned flags,
909 int *end_index, void *input)
911 error_t err;
912 struct parser parser;
914 /* If true, then err == EBADKEY is a result of a non-option argument failing
915 to be parsed (which in some cases isn't actually an error). */
916 int arg_ebadkey = 0;
918 if (! (flags & ARGP_NO_HELP))
919 /* Add our own options. */
921 struct argp_child *child = alloca (4 * sizeof (struct argp_child));
922 struct argp *top_argp = alloca (sizeof (struct argp));
924 /* TOP_ARGP has no options, it just serves to group the user & default
925 argps. */
926 memset (top_argp, 0, sizeof (*top_argp));
927 top_argp->children = child;
929 memset (child, 0, 4 * sizeof (struct argp_child));
931 if (argp)
932 (child++)->argp = argp;
933 (child++)->argp = &argp_default_argp;
934 if (argp_program_version || argp_program_version_hook)
935 (child++)->argp = &argp_version_argp;
936 child->argp = 0;
938 argp = top_argp;
941 /* Construct a parser for these arguments. */
942 err = parser_init (&parser, argp, argc, argv, flags, input);
944 if (! err)
945 /* Parse! */
947 while (! err)
948 err = parser_parse_next (&parser, &arg_ebadkey);
949 err = parser_finalize (&parser, err, arg_ebadkey, end_index);
952 return err;
954 #ifdef weak_alias
955 weak_alias (__argp_parse, argp_parse)
956 #endif
958 /* Return the input field for ARGP in the parser corresponding to STATE; used
959 by the help routines. */
960 void *
961 __argp_input (const struct argp *argp, const struct argp_state *state)
963 if (state)
965 struct group *group;
966 struct parser *parser = state->pstate;
968 for (group = parser->groups; group < parser->egroup; group++)
969 if (group->argp == argp)
970 return group->input;
973 return 0;
975 #ifdef weak_alias
976 weak_alias (__argp_input, _argp_input)
977 #endif