source: git/Singular/getopt.c @ 2c694a2

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