source: git/Singular/fegetopt.c @ c06a32

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