BSD 4_4_Lite2 development
[unix-history] / usr / src / contrib / gawk-2.15.2 / getopt.c
CommitLineData
a7e7e130
C
1/* Getopt for GNU.
2 NOTE: getopt is now part of the C library, so if you don't know what
3 "Keep this file name-space clean" means, talk to roland@gnu.ai.mit.edu
4 before changing it!
5
6 Copyright (C) 1987, 88, 89, 90, 91, 1992 Free Software Foundation, Inc.
7
8 This program is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Library General Public License as published
10 by the Free Software Foundation; either version 2, or (at your option)
11 any later version.
12
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU Library General Public
19 License along with this program; if not, write to the Free Software
20 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
21\f
22#ifdef GAWK
23#include "config.h"
24#endif
25
26#include <stdio.h>
27
28/* This needs to come after some library #include
29 to get __GNU_LIBRARY__ defined. */
30#ifdef __GNU_LIBRARY__
31#include <stdlib.h>
32#include <string.h>
33#endif /* GNU C library. */
34
35
36#ifndef __STDC__
37#define const
38#endif
39
40/* If GETOPT_COMPAT is defined, `+' as well as `--' can introduce a
41 long-named option. Because this is not POSIX.2 compliant, it is
42 being phased out. */
43#define GETOPT_COMPAT
44
45/* This version of `getopt' appears to the caller like standard Unix `getopt'
46 but it behaves differently for the user, since it allows the user
47 to intersperse the options with the other arguments.
48
49 As `getopt' works, it permutes the elements of ARGV so that,
50 when it is done, all the options precede everything else. Thus
51 all application programs are extended to handle flexible argument order.
52
53 Setting the environment variable POSIXLY_CORRECT disables permutation.
54 Then the behavior is completely standard.
55
56 GNU application programs can use a third alternative mode in which
57 they can distinguish the relative order of options and other arguments. */
58
59#include "getopt.h"
60
61/* For communication from `getopt' to the caller.
62 When `getopt' finds an option that takes an argument,
63 the argument value is returned here.
64 Also, when `ordering' is RETURN_IN_ORDER,
65 each non-option ARGV-element is returned here. */
66
67char *optarg = 0;
68
69/* Index in ARGV of the next element to be scanned.
70 This is used for communication to and from the caller
71 and for communication between successive calls to `getopt'.
72
73 On entry to `getopt', zero means this is the first call; initialize.
74
75 When `getopt' returns EOF, this is the index of the first of the
76 non-option elements that the caller should itself scan.
77
78 Otherwise, `optind' communicates from one call to the next
79 how much of ARGV has been scanned so far. */
80
81int optind = 0;
82
83/* The next char to be scanned in the option-element
84 in which the last option character we returned was found.
85 This allows us to pick up the scan where we left off.
86
87 If this is zero, or a null string, it means resume the scan
88 by advancing to the next ARGV-element. */
89
90static char *nextchar;
91
92/* Callers store zero here to inhibit the error message
93 for unrecognized options. */
94
95int opterr = 1;
96
97/* Describe how to deal with options that follow non-option ARGV-elements.
98
99 If the caller did not specify anything,
100 the default is REQUIRE_ORDER if the environment variable
101 POSIXLY_CORRECT is defined, PERMUTE otherwise.
102
103 REQUIRE_ORDER means don't recognize them as options;
104 stop option processing when the first non-option is seen.
105 This is what Unix does.
106 This mode of operation is selected by either setting the environment
107 variable POSIXLY_CORRECT, or using `+' as the first character
108 of the list of option characters.
109
110 PERMUTE is the default. We permute the contents of ARGV as we scan,
111 so that eventually all the non-options are at the end. This allows options
112 to be given in any order, even with programs that were not written to
113 expect this.
114
115 RETURN_IN_ORDER is an option available to programs that were written
116 to expect options and other ARGV-elements in any order and that care about
117 the ordering of the two. We describe each non-option ARGV-element
118 as if it were the argument of an option with character code 1.
119 Using `-' as the first character of the list of option characters
120 selects this mode of operation.
121
122 The special argument `--' forces an end of option-scanning regardless
123 of the value of `ordering'. In the case of RETURN_IN_ORDER, only
124 `--' can cause `getopt' to return EOF with `optind' != ARGC. */
125
126static enum
127{
128 REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
129} ordering;
130\f
131#ifdef __GNU_LIBRARY__
132#include <string.h>
133#define my_index strchr
134#define my_bcopy(src, dst, n) memcpy ((dst), (src), (n))
135#else
136
137/* Avoid depending on library functions or files
138 whose names are inconsistent. */
139
140char *getenv ();
141
142static char *
143my_index (string, chr)
144 char *string;
145 int chr;
146{
147 while (*string)
148 {
149 if (*string == chr)
150 return string;
151 string++;
152 }
153 return 0;
154}
155
156static void
157my_bcopy (from, to, size)
158 char *from, *to;
159 int size;
160{
161 int i;
162 for (i = 0; i < size; i++)
163 to[i] = from[i];
164}
165#endif /* GNU C library. */
166\f
167/* Handle permutation of arguments. */
168
169/* Describe the part of ARGV that contains non-options that have
170 been skipped. `first_nonopt' is the index in ARGV of the first of them;
171 `last_nonopt' is the index after the last of them. */
172
173static int first_nonopt;
174static int last_nonopt;
175
176/* Exchange two adjacent subsequences of ARGV.
177 One subsequence is elements [first_nonopt,last_nonopt)
178 which contains all the non-options that have been skipped so far.
179 The other is elements [last_nonopt,optind), which contains all
180 the options processed since those non-options were skipped.
181
182 `first_nonopt' and `last_nonopt' are relocated so that they describe
183 the new indices of the non-options in ARGV after they are moved. */
184
185static void
186exchange (argv)
187 char **argv;
188{
189 int nonopts_size = (last_nonopt - first_nonopt) * sizeof (char *);
190 char **temp = (char **) malloc (nonopts_size);
191
192 /* Interchange the two blocks of data in ARGV. */
193
194 my_bcopy (&argv[first_nonopt], temp, nonopts_size);
195 my_bcopy (&argv[last_nonopt], &argv[first_nonopt],
196 (optind - last_nonopt) * sizeof (char *));
197 my_bcopy (temp, &argv[first_nonopt + optind - last_nonopt], nonopts_size);
198
199 free(temp);
200
201 /* Update records for the slots the non-options now occupy. */
202
203 first_nonopt += (optind - last_nonopt);
204 last_nonopt = optind;
205}
206\f
207/* Scan elements of ARGV (whose length is ARGC) for option characters
208 given in OPTSTRING.
209
210 If an element of ARGV starts with '-', and is not exactly "-" or "--",
211 then it is an option element. The characters of this element
212 (aside from the initial '-') are option characters. If `getopt'
213 is called repeatedly, it returns successively each of the option characters
214 from each of the option elements.
215
216 If `getopt' finds another option character, it returns that character,
217 updating `optind' and `nextchar' so that the next call to `getopt' can
218 resume the scan with the following option character or ARGV-element.
219
220 If there are no more option characters, `getopt' returns `EOF'.
221 Then `optind' is the index in ARGV of the first ARGV-element
222 that is not an option. (The ARGV-elements have been permuted
223 so that those that are not options now come last.)
224
225 OPTSTRING is a string containing the legitimate option characters.
226 If an option character is seen that is not listed in OPTSTRING,
227 return '?' after printing an error message. If you set `opterr' to
228 zero, the error message is suppressed but we still return '?'.
229
230 If a char in OPTSTRING is followed by a colon, that means it wants an arg,
231 so the following text in the same ARGV-element, or the text of the following
232 ARGV-element, is returned in `optarg'. Two colons mean an option that
233 wants an optional arg; if there is text in the current ARGV-element,
234 it is returned in `optarg', otherwise `optarg' is set to zero.
235
236 If OPTSTRING starts with `-' or `+', it requests different methods of
237 handling the non-option ARGV-elements.
238 See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
239
240 Long-named options begin with `--' instead of `-'.
241 Their names may be abbreviated as long as the abbreviation is unique
242 or is an exact match for some defined option. If they have an
243 argument, it follows the option name in the same ARGV-element, separated
244 from the option name by a `=', or else the in next ARGV-element.
245 When `getopt' finds a long-named option, it returns 0 if that option's
246 `flag' field is nonzero, the value of the option's `val' field
247 if the `flag' field is zero.
248
249 The elements of ARGV aren't really const, because we permute them.
250 But we pretend they're const in the prototype to be compatible
251 with other systems.
252
253 LONGOPTS is a vector of `struct option' terminated by an
254 element containing a name which is zero.
255
256 LONGIND returns the index in LONGOPT of the long-named option found.
257 It is only valid when a long-named option has been found by the most
258 recent call.
259
260 If LONG_ONLY is nonzero, '-' as well as '--' can introduce
261 long-named options. */
262
263int
264_getopt_internal (argc, argv, optstring, longopts, longind, long_only)
265 int argc;
266 char *const *argv;
267 const char *optstring;
268 const struct option *longopts;
269 int *longind;
270 int long_only;
271{
272 int option_index;
273
274 optarg = 0;
275
276 /* Initialize the internal data when the first call is made.
277 Start processing options with ARGV-element 1 (since ARGV-element 0
278 is the program name); the sequence of previously skipped
279 non-option ARGV-elements is empty. */
280
281 if (optind == 0)
282 {
283 first_nonopt = last_nonopt = optind = 1;
284
285 nextchar = NULL;
286
287 /* Determine how to handle the ordering of options and nonoptions. */
288
289 if (optstring[0] == '-')
290 {
291 ordering = RETURN_IN_ORDER;
292 ++optstring;
293 }
294 else if (optstring[0] == '+')
295 {
296 ordering = REQUIRE_ORDER;
297 ++optstring;
298 }
299 else if (getenv ("POSIXLY_CORRECT") != NULL)
300 ordering = REQUIRE_ORDER;
301 else
302 ordering = PERMUTE;
303 }
304
305 if (nextchar == NULL || *nextchar == '\0')
306 {
307 if (ordering == PERMUTE)
308 {
309 /* If we have just processed some options following some non-options,
310 exchange them so that the options come first. */
311
312 if (first_nonopt != last_nonopt && last_nonopt != optind)
313 exchange ((char **) argv);
314 else if (last_nonopt != optind)
315 first_nonopt = optind;
316
317 /* Now skip any additional non-options
318 and extend the range of non-options previously skipped. */
319
320 while (optind < argc
321 && (argv[optind][0] != '-' || argv[optind][1] == '\0')
322#ifdef GETOPT_COMPAT
323 && (longopts == NULL
324 || argv[optind][0] != '+' || argv[optind][1] == '\0')
325#endif /* GETOPT_COMPAT */
326 )
327 optind++;
328 last_nonopt = optind;
329 }
330
331 /* Special ARGV-element `--' means premature end of options.
332 Skip it like a null option,
333 then exchange with previous non-options as if it were an option,
334 then skip everything else like a non-option. */
335
336 if (optind != argc && !strcmp (argv[optind], "--"))
337 {
338 optind++;
339
340 if (first_nonopt != last_nonopt && last_nonopt != optind)
341 exchange ((char **) argv);
342 else if (first_nonopt == last_nonopt)
343 first_nonopt = optind;
344 last_nonopt = argc;
345
346 optind = argc;
347 }
348
349 /* If we have done all the ARGV-elements, stop the scan
350 and back over any non-options that we skipped and permuted. */
351
352 if (optind == argc)
353 {
354 /* Set the next-arg-index to point at the non-options
355 that we previously skipped, so the caller will digest them. */
356 if (first_nonopt != last_nonopt)
357 optind = first_nonopt;
358 return EOF;
359 }
360
361 /* If we have come to a non-option and did not permute it,
362 either stop the scan or describe it to the caller and pass it by. */
363
364 if ((argv[optind][0] != '-' || argv[optind][1] == '\0')
365#ifdef GETOPT_COMPAT
366 && (longopts == NULL
367 || argv[optind][0] != '+' || argv[optind][1] == '\0')
368#endif /* GETOPT_COMPAT */
369 )
370 {
371 if (ordering == REQUIRE_ORDER)
372 return EOF;
373 optarg = argv[optind++];
374 return 1;
375 }
376
377 /* We have found another option-ARGV-element.
378 Start decoding its characters. */
379
380 nextchar = (argv[optind] + 1
381 + (longopts != NULL && argv[optind][1] == '-'));
382 }
383
384 if (longopts != NULL
385 && ((argv[optind][0] == '-'
386 && (argv[optind][1] == '-' || long_only))
387#ifdef GETOPT_COMPAT
388 || argv[optind][0] == '+'
389#endif /* GETOPT_COMPAT */
390 ))
391 {
392 const struct option *p;
393 char *s = nextchar;
394 int exact = 0;
395 int ambig = 0;
396 const struct option *pfound = NULL;
397 int indfound = 0;
398 extern int strncmp();
399
400 while (*s && *s != '=')
401 s++;
402
403 /* Test all options for either exact match or abbreviated matches. */
404 for (p = longopts, option_index = 0; p->name;
405 p++, option_index++)
406 if (!strncmp (p->name, nextchar, s - nextchar))
407 {
408 if (s - nextchar == strlen (p->name))
409 {
410 /* Exact match found. */
411 pfound = p;
412 indfound = option_index;
413 exact = 1;
414 break;
415 }
416 else if (pfound == NULL)
417 {
418 /* First nonexact match found. */
419 pfound = p;
420 indfound = option_index;
421 }
422 else
423 /* Second nonexact match found. */
424 ambig = 1;
425 }
426
427 if (ambig && !exact)
428 {
429 if (opterr)
430 fprintf (stderr, "%s: option `%s' is ambiguous\n",
431 argv[0], argv[optind]);
432 nextchar += strlen (nextchar);
433 optind++;
434 return '?';
435 }
436
437 if (pfound != NULL)
438 {
439 option_index = indfound;
440 optind++;
441 if (*s)
442 {
443 /* Don't test has_arg with >, because some C compilers don't
444 allow it to be used on enums. */
445 if (pfound->has_arg)
446 optarg = s + 1;
447 else
448 {
449 if (opterr)
450 {
451 if (argv[optind - 1][1] == '-')
452 /* --option */
453 fprintf (stderr,
454 "%s: option `--%s' doesn't allow an argument\n",
455 argv[0], pfound->name);
456 else
457 /* +option or -option */
458 fprintf (stderr,
459 "%s: option `%c%s' doesn't allow an argument\n",
460 argv[0], argv[optind - 1][0], pfound->name);
461 }
462 nextchar += strlen (nextchar);
463 return '?';
464 }
465 }
466 else if (pfound->has_arg == 1)
467 {
468 if (optind < argc)
469 optarg = argv[optind++];
470 else
471 {
472 if (opterr)
473 fprintf (stderr, "%s: option `%s' requires an argument\n",
474 argv[0], argv[optind - 1]);
475 nextchar += strlen (nextchar);
476 return '?';
477 }
478 }
479 nextchar += strlen (nextchar);
480 if (longind != NULL)
481 *longind = option_index;
482 if (pfound->flag)
483 {
484 *(pfound->flag) = pfound->val;
485 return 0;
486 }
487 return pfound->val;
488 }
489 /* Can't find it as a long option. If this is not getopt_long_only,
490 or the option starts with '--' or is not a valid short
491 option, then it's an error.
492 Otherwise interpret it as a short option. */
493 if (!long_only || argv[optind][1] == '-'
494#ifdef GETOPT_COMPAT
495 || argv[optind][0] == '+'
496#endif /* GETOPT_COMPAT */
497 || my_index (optstring, *nextchar) == NULL)
498 {
499 if (opterr)
500 {
501 if (argv[optind][1] == '-')
502 /* --option */
503 fprintf (stderr, "%s: unrecognized option `--%s'\n",
504 argv[0], nextchar);
505 else
506 /* +option or -option */
507 fprintf (stderr, "%s: unrecognized option `%c%s'\n",
508 argv[0], argv[optind][0], nextchar);
509 }
510 nextchar = (char *) "";
511 optind++;
512 return '?';
513 }
514 }
515
516 /* Look at and handle the next option-character. */
517
518 {
519 char c = *nextchar++;
520 char *temp = my_index (optstring, c);
521
522 /* Increment `optind' when we start to process its last character. */
523 if (*nextchar == '\0')
524 ++optind;
525
526 if (temp == NULL || c == ':')
527 {
528 if (opterr)
529 {
530 if (c < 040 || c >= 0177)
531 fprintf (stderr, "%s: unrecognized option, character code 0%o\n",
532 argv[0], c);
533 else
534 fprintf (stderr, "%s: unrecognized option `-%c'\n", argv[0], c);
535 }
536 return '?';
537 }
538 if (temp[1] == ':')
539 {
540 if (temp[2] == ':')
541 {
542 /* This is an option that accepts an argument optionally. */
543 if (*nextchar != '\0')
544 {
545 optarg = nextchar;
546 optind++;
547 }
548 else
549 optarg = 0;
550 nextchar = NULL;
551 }
552 else
553 {
554 /* This is an option that requires an argument. */
555 if (*nextchar != '\0')
556 {
557 optarg = nextchar;
558 /* If we end this ARGV-element by taking the rest as an arg,
559 we must advance to the next element now. */
560 optind++;
561 }
562 else if (optind == argc)
563 {
564 if (opterr)
565 fprintf (stderr, "%s: option `-%c' requires an argument\n",
566 argv[0], c);
567 c = '?';
568 }
569 else
570 /* We already incremented `optind' once;
571 increment it again when taking next ARGV-elt as argument. */
572 optarg = argv[optind++];
573 nextchar = NULL;
574 }
575 }
576 return c;
577 }
578}
579
580int
581getopt (argc, argv, optstring)
582 int argc;
583 char *const *argv;
584 const char *optstring;
585{
586 return _getopt_internal (argc, argv, optstring,
587 (const struct option *) 0,
588 (int *) 0,
589 0);
590}
591\f
592#ifdef TEST
593
594/* Compile with -DTEST to make an executable for use in testing
595 the above definition of `getopt'. */
596
597int
598main (argc, argv)
599 int argc;
600 char **argv;
601{
602 int c;
603 int digit_optind = 0;
604
605 while (1)
606 {
607 int this_option_optind = optind ? optind : 1;
608
609 c = getopt (argc, argv, "abc:d:0123456789");
610 if (c == EOF)
611 break;
612
613 switch (c)
614 {
615 case '0':
616 case '1':
617 case '2':
618 case '3':
619 case '4':
620 case '5':
621 case '6':
622 case '7':
623 case '8':
624 case '9':
625 if (digit_optind != 0 && digit_optind != this_option_optind)
626 printf ("digits occur in two different argv-elements.\n");
627 digit_optind = this_option_optind;
628 printf ("option %c\n", c);
629 break;
630
631 case 'a':
632 printf ("option a\n");
633 break;
634
635 case 'b':
636 printf ("option b\n");
637 break;
638
639 case 'c':
640 printf ("option c with value `%s'\n", optarg);
641 break;
642
643 case '?':
644 break;
645
646 default:
647 printf ("?? getopt returned character code 0%o ??\n", c);
648 }
649 }
650
651 if (optind < argc)
652 {
653 printf ("non-option ARGV-elements: ");
654 while (optind < argc)
655 printf ("%s ", argv[optind++]);
656 printf ("\n");
657 }
658
659 exit (0);
660}
661
662#endif /* TEST */