source: git/Singular/fegetopt.c @ 4e654a2

spielwiese
Last change on this file since 4e654a2 was 762407, checked in by Oleksandr Motsak <motsak@…>, 12 years ago
config.h is for sources files only FIX: config.h should only be used by source (not from inside kernel/mod2.h!) NOTE: each source file should better include mod2.h right after config.h, while headers should better not include mod2.h.
  • Property mode set to 100644
File size: 23.9 KB
Line 
1/****************************************
2*  Computer Algebra System SINGULAR     *
3****************************************/
4/* $Id$ */
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 "config.h"
36#include <kernel/mod2.h>
37
38#ifndef __STDC__
39#  ifndef const
40#    define const
41#  endif
42#endif
43
44/* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>.  */
45#ifndef _NO_PROTO
46#define _NO_PROTO
47#endif
48
49#include <stdio.h>
50/* #include "tailor.h" */
51
52/* Comment out all this code if we are using the GNU C Library, and are not
53   actually compiling the library itself.  This code is part of the GNU C
54   Library, but also included in many other GNU distributions.  Compiling
55   and linking in this code is a waste when using the GNU C library
56   (especially if it is a shared library).  Rather than having every GNU
57   program understand `configure --with-gnu-libc' and omit the object files,
58   it is simpler to just do this in the source for each such file.  */
59
60/* This needs to come after some library #include
61   to get __GNU_LIBRARY__ defined.  */
62#ifdef  __GNU_LIBRARY__
63/* Don't include stdlib.h for non-GNU C libraries because some of them
64   contain conflicting prototypes for getopt.  */
65#include <stdlib.h>
66#endif  /* GNU C library.  */
67
68/* If GETOPT_COMPAT is defined, `+' as well as `--' can introduce a
69   long-named option.  Because this is not POSIX.2 compliant, it is
70   being phased out.  */
71/* #define GETOPT_COMPAT */
72
73/* This version of `getopt' appears to the caller like standard Unix `getopt'
74   but it behaves differently for the user, since it allows the user
75   to intersperse the options with the other arguments.
76
77   As `getopt' works, it permutes the elements of ARGV so that,
78   when it is done, all the options precede everything else.  Thus
79   all application programs are extended to handle flexible argument order.
80
81   Setting the environment variable POSIXLY_CORRECT disables permutation.
82   Then the behavior is completely standard.
83
84   GNU application programs can use a third alternative mode in which
85   they can distinguish the relative order of options and other arguments.  */
86
87#include <Singular/fegetopt.h>
88
89/* For communication from `getopt' to the caller.
90   When `getopt' finds an option that takes an argument,
91   the argument value is returned here.
92   Also, when `ordering' is RETURN_IN_ORDER,
93   each non-option ARGV-element is returned here.  */
94
95char *fe_optarg = 0;
96
97/* Index in ARGV of the next element to be scanned.
98   This is used for communication to and from the caller
99   and for communication between successive calls to `getopt'.
100
101   On entry to `getopt', zero means this is the first call; initialize.
102
103   When `getopt' returns EOF, this is the index of the first of the
104   non-option elements that the caller should itself scan.
105
106   Otherwise, `fe_optind' communicates from one call to the next
107   how much of ARGV has been scanned so far.  */
108
109/* XXX 1003.2 says this must be 1 before any call.  */
110int fe_optind = 0;
111
112/* The next char to be scanned in the option-element
113   in which the last option character we returned was found.
114   This allows us to pick up the scan where we left off.
115
116   If this is zero, or a null string, it means resume the scan
117   by advancing to the next ARGV-element.  */
118
119static char *nextchar;
120
121/* Callers store zero here to inhibit the error message
122   for unrecognized options.  */
123
124int fe_opterr = 1;
125
126/* Set to an option character which was unrecognized.
127   This must be initialized on some systems to avoid linking in the
128   system's own getopt implementation.  */
129
130#define BAD_OPTION '\0'
131int fe_optopt = BAD_OPTION;
132
133/* Describe how to deal with options that follow non-option ARGV-elements.
134
135   If the caller did not specify anything,
136   the default is REQUIRE_ORDER if the environment variable
137   POSIXLY_CORRECT is defined, PERMUTE otherwise.
138
139   REQUIRE_ORDER means don't recognize them as options;
140   stop option processing when the first non-option is seen.
141   This is what Unix does.
142   This mode of operation is selected by either setting the environment
143   variable POSIXLY_CORRECT, or using `+' as the first character
144   of the list of option characters.
145
146   PERMUTE is the default.  We permute the contents of ARGV as we scan,
147   so that eventually all the non-options are at the end.  This allows options
148   to be given in any order, even with programs that were not written to
149   expect this.
150
151   RETURN_IN_ORDER is an option available to programs that were written
152   to expect options and other ARGV-elements in any order and that care about
153   the ordering of the two.  We describe each non-option ARGV-element
154   as if it were the argument of an option with character code 1.
155   Using `-' as the first character of the list of option characters
156   selects this mode of operation.
157
158   The special argument `--' forces an end of option-scanning regardless
159   of the value of `ordering'.  In the case of RETURN_IN_ORDER, only
160   `--' can cause `getopt' to return EOF with `fe_optind' != ARGC.  */
161
162static enum
163{
164  REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
165} ordering;
166
167#ifdef  __GNU_LIBRARY__
168/* We want to avoid inclusion of string.h with non-GNU libraries
169   because there are many ways it can cause trouble.
170   On some systems, it contains special magic macros that don't work
171   in GCC.  */
172#include <string.h>
173#define my_index        strchr
174#define my_strlen       strlen
175#else
176
177/* Avoid depending on library functions or files
178   whose names are inconsistent.  */
179
180#if __STDC__ || defined(PROTO)
181extern char *getenv(const char *name);
182extern int  strcmp (const char *s1, const char *s2);
183/*extern int  strncmp(const char *s1, const char *s2, int n);*/
184
185static int my_strlen(const char *s);
186static const char *my_index (const char *str, int chr);
187#else
188extern char *getenv ();
189#endif
190
191static int my_strlen (const char *str)
192{
193  int n = 0;
194  while (*str++)
195    n++;
196  return n;
197}
198
199static const char * my_index (const char *str, int chr)
200{
201  while (*str)
202    {
203      if (*str == chr)
204        return (const char *) str;
205      str++;
206    }
207  return 0;
208}
209
210#endif                          /* GNU C library.  */
211
212/* Handle permutation of arguments.  */
213
214/* Describe the part of ARGV that contains non-options that have
215   been skipped.  `first_nonopt' is the index in ARGV of the first of them;
216   `last_nonopt' is the index after the last of them.  */
217
218static int first_nonopt;
219static int last_nonopt;
220
221/* Exchange two adjacent subsequences of ARGV.
222   One subsequence is elements [first_nonopt,last_nonopt)
223   which contains all the non-options that have been skipped so far.
224   The other is elements [last_nonopt,fe_optind), which contains all
225   the options processed since those non-options were skipped.
226
227   `first_nonopt' and `last_nonopt' are relocated so that they describe
228   the new indices of the non-options in ARGV after they are moved.
229
230   To perform the swap, we first reverse the order of all elements. So
231   all options now come before all non options, but they are in the
232   wrong order. So we put back the options and non options in original
233   order by reversing them again. For example:
234       original input:      a b c -x -y
235       reverse all:         -y -x c b a
236       reverse options:     -x -y c b a
237       reverse non options: -x -y a b c
238*/
239
240#if __STDC__ || defined(PROTO)
241static void exchange (char **argv);
242#endif
243
244static void exchange (char **argv)
245{
246  char *temp, **first, **last;
247
248  /* Reverse all the elements [first_nonopt, fe_optind) */
249  first = &argv[first_nonopt];
250  last  = &argv[fe_optind-1];
251  while (first < last) {
252    temp = *first; *first = *last; *last = temp; first++; last--;
253  }
254  /* Put back the options in order */
255  first = &argv[first_nonopt];
256  first_nonopt += (fe_optind - last_nonopt);
257  last  = &argv[first_nonopt - 1];
258  while (first < last) {
259    temp = *first; *first = *last; *last = temp; first++; last--;
260  }
261
262  /* Put back the non options in order */
263  first = &argv[first_nonopt];
264  last_nonopt = fe_optind;
265  last  = &argv[last_nonopt-1];
266  while (first < last) {
267    temp = *first; *first = *last; *last = temp; first++; last--;
268  }
269}
270
271/* Scan elements of ARGV (whose length is ARGC) for option characters
272   given in OPTSTRING.
273
274   If an element of ARGV starts with '-', and is not exactly "-" or "--",
275   then it is an option element.  The characters of this element
276   (aside from the initial '-') are option characters.  If `getopt'
277   is called repeatedly, it returns successively each of the option characters
278   from each of the option elements.
279
280   If `getopt' finds another option character, it returns that character,
281   updating `fe_optind' and `nextchar' so that the next call to `getopt' can
282   resume the scan with the following option character or ARGV-element.
283
284   If there are no more option characters, `getopt' returns `EOF'.
285   Then `fe_optind' is the index in ARGV of the first ARGV-element
286   that is not an option.  (The ARGV-elements have been permuted
287   so that those that are not options now come last.)
288
289   OPTSTRING is a string containing the legitimate option characters.
290   If an option character is seen that is not listed in OPTSTRING,
291   return BAD_OPTION after printing an error message.  If you set `fe_opterr' to
292   zero, the error message is suppressed but we still return BAD_OPTION.
293
294   If a char in OPTSTRING is followed by a colon, that means it wants an arg,
295   so the following text in the same ARGV-element, or the text of the following
296   ARGV-element, is returned in `fe_optarg'.  Two colons mean an option that
297   wants an optional arg; if there is text in the current ARGV-element,
298   it is returned in `fe_optarg', otherwise `fe_optarg' is set to zero.
299
300   If OPTSTRING starts with `-' or `+', it requests different methods of
301   handling the non-option ARGV-elements.
302   See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
303
304   Long-named options begin with `--' instead of `-'.
305   Their names may be abbreviated as long as the abbreviation is unique
306   or is an exact match for some defined option.  If they have an
307   argument, it follows the option name in the same ARGV-element, separated
308   from the option name by a `=', or else the in next ARGV-element.
309   When `getopt' finds a long-named option, it returns
310   the value of the option's `val' field.
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          return pfound->val;
544        }
545      /* Can't find it as a long option.  If this is not getopt_long_only,
546         or the option starts with '--' or is not a valid short
547         option, then it's an error.
548         Otherwise interpret it as a short option.  */
549      if (!long_only || argv[fe_optind][1] == '-'
550#ifdef GETOPT_COMPAT
551          || argv[fe_optind][0] == '+'
552#endif                          /* GETOPT_COMPAT */
553          || my_index (optstring, *nextchar) == NULL)
554        {
555          if (fe_opterr)
556            {
557              if (argv[fe_optind][1] == '-')
558                /* --option */
559                fprintf (stderr, "%s: unrecognized option `--%s'\n",
560                         argv[0], nextchar);
561              else
562                /* +option or -option */
563                fprintf (stderr, "%s: unrecognized option `%c%s'\n",
564                         argv[0], argv[fe_optind][0], nextchar);
565            }
566          nextchar = (char *) "";
567          fe_optind++;
568          return BAD_OPTION;
569        }
570    }
571
572  /* Look at and handle the next option-character.  */
573
574  {
575    char c = *nextchar++;
576    const char *temp = my_index (optstring, c);
577
578    /* Increment `fe_optind' when we start to process its last character.  */
579    if (*nextchar == '\0')
580      ++fe_optind;
581
582    if (temp == NULL || c == ':')
583      {
584        if (fe_opterr)
585          {
586#if 0
587            if (c < 040 || c >= 0177)
588              fprintf (stderr, "%s: unrecognized option, character code 0%o\n",
589                       argv[0], c);
590            else
591              fprintf (stderr, "%s: unrecognized option `-%c'\n", argv[0], c);
592#else
593            /* 1003.2 specifies the format of this message.  */
594            fprintf (stderr, "%s: illegal option -- %c\n", argv[0], c);
595#endif
596          }
597        fe_optopt = c;
598        return BAD_OPTION;
599      }
600    if (temp[1] == ':')
601      {
602        if (temp[2] == ':')
603          {
604            /* This is an option that accepts an argument optionally.  */
605            if (*nextchar != '\0')
606              {
607                fe_optarg = nextchar;
608                fe_optind++;
609              }
610            else
611              fe_optarg = 0;
612            nextchar = NULL;
613          }
614        else
615          {
616            /* This is an option that requires an argument.  */
617            if (*nextchar != '\0')
618              {
619                fe_optarg = nextchar;
620                /* If we end this ARGV-element by taking the rest as an arg,
621                   we must advance to the next element now.  */
622                fe_optind++;
623              }
624            else if (fe_optind == argc)
625              {
626                if (fe_opterr)
627                  {
628#if 0
629                    fprintf (stderr, "%s: option `-%c' requires an argument\n",
630                             argv[0], c);
631#else
632                    /* 1003.2 specifies the format of this message.  */
633                    fprintf (stderr, "%s: option requires an argument -- %c\n",
634                             argv[0], c);
635#endif
636                  }
637                fe_optopt = c;
638                if (optstring[0] == ':')
639                  c = ':';
640                else
641                  c = BAD_OPTION;
642              }
643            else
644              /* We already incremented `fe_optind' once;
645                 increment it again when taking next ARGV-elt as argument.  */
646              fe_optarg = argv[fe_optind++];
647            nextchar = NULL;
648          }
649      }
650    return c;
651  }
652}
653
654int fe_getopt (
655     int argc,
656     char *const *argv,
657     const char *optstring)
658{
659  return _fe_getopt_internal (argc, argv, optstring,
660                           (const struct fe_option *) 0,
661                           (int *) 0,
662                           0);
663}
664
665int fe_getopt_long (
666     int argc,
667     char *const *argv,
668     const char *options,
669     const struct fe_option *long_options,
670     int *opt_index)
671{
672  return _fe_getopt_internal (argc, argv, options, long_options, opt_index, 0);
673}
674
675int fe_getopt_long_only (
676     int argc,
677     char *const *argv,
678     const char *options,
679     const struct fe_option *long_options,
680     int *opt_index)
681{
682  return _fe_getopt_internal (argc, argv, options, long_options, opt_index, 1);
683}
684
685#ifdef TEST_GETOPT
686
687/* Compile with -DTEST_GETOPT to make an executable for use in testing
688   the above definition of `getopt'.  */
689
690int main (int argc, char **argv)
691{
692  int c;
693  int digit_optind = 0;
694
695  while (1)
696    {
697      int this_option_optind = optind ? optind : 1;
698
699      c = fe_getopt (argc, argv, "abc:d:0123456789");
700      if (c == EOF)
701        break;
702
703      switch (c)
704        {
705        case '0':
706        case '1':
707        case '2':
708        case '3':
709        case '4':
710        case '5':
711        case '6':
712        case '7':
713        case '8':
714        case '9':
715          if (digit_optind != 0 && digit_optind != this_option_optind)
716            printf ("digits occur in two different argv-elements.\n");
717          digit_optind = this_option_optind;
718          printf ("option %c\n", c);
719          break;
720
721        case 'a':
722          printf ("option a\n");
723          break;
724
725        case 'b':
726          printf ("option b\n");
727          break;
728
729        case 'c':
730          printf ("option c with value `%s'\n", fe_optarg);
731          break;
732
733        case BAD_OPTION:
734          break;
735
736        default:
737          printf ("?? fe_getopt returned character code 0%o ??\n", c);
738        }
739    }
740
741  if (fe_optind < argc)
742    {
743      printf ("non-option ARGV-elements: ");
744      while (fe_optind < argc)
745        printf ("%s ", argv[fe_optind++]);
746      printf ("\n");
747    }
748
749  exit (0);
750}
751
752#endif /* TEST_GETOPT */
Note: See TracBrowser for help on using the repository browser.