chiark / gitweb /
debian/control: Recommend the other build tools we usually need.
[cfd] / mdwopt.h
1 /* -*-c-*-
2  *
3  * Options parsing, similar to GNU @getopt_long@
4  *
5  * (c) 1996 Straylight/Edgeware
6  */
7
8 /*----- Licensing notice --------------------------------------------------*
9  *
10  * This file is part of many programs.
11  *
12  * `mdwopt' is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU Library General Public License as
14  * published by the Free Software Foundation; either version 2 of the
15  * License, or (at your option) any later version.
16  *
17  * `mdwopt' is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU Library General Public License for more details.
21  *
22  * You should have received a copy of the GNU Library General Public
23  * License along with `mdwopt'; if not, write to the Free
24  * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
25  * MA 02111-1307, USA.
26  */
27
28 #ifndef MDWOPT_H
29 #define MDWOPT_H
30
31 /*----- Options handling structures ---------------------------------------*/
32
33 #ifdef __cplusplus
34   extern "C" {
35 #endif
36
37 /* --- @mdwopt_data@ --- *
38  *
39  * Contains all the information needed by the @mdwopt@ routine to do its
40  * work.  Try not to use @prog@ any more.  If you're using mLib, the @quis@/
41  * @ego@ interface works better.
42  */
43
44 typedef struct {
45
46   /* --- Public variables --- */
47
48   char *arg;                            /* Arg of current option, or 0 */
49   int opt;                              /* Value of current option */
50   int ind;                              /* 0 for init, index when done */
51   int err;                              /* Set nonzero for error messages */
52   char *prog;                           /* Program name (from @argv[0]@) */
53
54   /* --- Private variables --- *
55    *
56    * Don't play with these, please.
57    */
58
59   char *list;                           /* Current short options pointer */
60   int next;                             /* Next argument, unpermuted */
61   int order;                            /* Ordering of options, flags */
62   char *env;                            /* Where we are in the env var */
63   char *estart;                         /* Pointer to env var buffer */
64 }
65 mdwopt_data;
66
67 /*----- Global variables --------------------------------------------------*/
68
69 extern mdwopt_data mdwopt_global;       /* The default global data */
70
71 /* --- For compatibility with older programs (and prettiness) --- *
72  *
73  * The macros here access the global structure defined above.  I consider it
74  * to be perfectly acceptable to use these macros in new code, because it
75  * looks nicer than playing with @mdwopt_global@.
76  */
77
78 #define optarg (mdwopt_global.arg)      /* Argument of current option */
79 #define optopt (mdwopt_global.opt)      /* Code of current option */
80 #define opterr (mdwopt_global.err)      /* Zero to report error messages */
81 #define optind (mdwopt_global.ind)      /* Index of first non-option */
82 #define optprog (mdwopt_global.prog)    /* Pointer to program name */
83
84 /*----- Type definitions --------------------------------------------------*/
85
86 /* --- Long options definition table --- */
87
88 struct option {
89   const char *name;                     /* Name of the long option */
90   int has_arg;                          /* Does it have an argument? */
91   int *flag;                            /* Address of flag variable */
92   int val;                              /* Value to store/return */
93 };
94
95 /* --- Old-style names for argument flags in long options table --- */
96
97 enum {
98   no_argument,                          /* No argument required */
99   required_argument,                    /* User must specify argument */
100   optional_argument                     /* Argument is optional */
101 };
102
103 /* --- New style flag names --- */
104
105 #define OPTF_NOARG 0u                   /* No argument */
106 #define OPTF_ARGREQ 1u                  /* Required argument */
107 #define OPTF_ARGOPT 2u                  /* Optional argument */
108 #define OPTF_ARG 3u                     /* Argument type bitmask */
109 #define OPTF_SWITCH 4u                  /* OR val into flag, don't store */
110 #define OPTF_NEGATE 8u                  /* Allow long option to be negated */
111
112 #define OPTF_NOLONGS 1u                 /* Don't read long options */
113 #define OPTF_NOSHORTS 2u                /* Don't read short options */
114 #define OPTF_NUMBERS 4u                 /* Read numeric options */
115 #define OPTF_NEGATION 8u                /* Allow `%|+|%' for negations */
116 #define OPTF_ENVVAR 16u                 /* Parse options from env var */
117 #define OPTF_NOPROGNAME 32u             /* Don't set @optprog@  */
118 #define OPTF_NEGNUMBER 64u              /* Allow negated number options */
119
120 #define OPTF_NEGATED 256u               /* Option flag was negated by user */
121
122 /* --- Older new-style names --- */
123
124 enum {
125   gFlag_argReq = 1, gFlag_argOpt = 2, gFlag_switch = 4, gFlag_negate = 8
126 };
127
128 enum {
129   gFlag_noLongs = 1, gFlag_noShorts = 2, gFlag_numbers = 4,
130   gFlag_negation = 8, gFlag_envVar = 16, gFlag_noProgName = 32,
131   gFlag_negNumber = 64
132 };
133
134 enum {
135   gFlag_negated = 256
136 };
137
138 /*----- Main code ---------------------------------------------------------*/
139
140 /* --- @mdwopt@ --- *
141  *
142  * Arguments:   @int argc@ = number of command line arguments
143  *              @char * const *argv@ = pointer to command line arguments
144  *              @const char *shortopt@ = pointer to short options information
145  *              @const struct option *longopts@ = pointer to long opts info
146  *              @int *longind@ = where to store matched longopt
147  *              @mdwopt_data *data@ = persistent state for the parser
148  *              @int flags@ = various useful flags
149  *
150  * Returns:     Value of option found next, or an error character, or
151  *              @EOF@ for the last thing.
152  *
153  * Use:         Reads options.  The routine should be more-or-less compatible
154  *              with standard getopts, although it provides many more
155  *              features even than the standard GNU implementation.
156  *
157  *              The precise manner of options parsing is determined by
158  *              various flag settings, which are described below.  By setting
159  *              flag values appropriately, you can achieve behaviour very
160  *              similar to most other getopt routines.
161  *
162  *
163  *          How options parsing appears to users
164  *
165  *              A command line consists of a number of `words' (which may
166  *              contain spaces, according to various shell quoting
167  *              conventions).  A word may be an option, an argument to an
168  *              option, or a non-option.  An option begins with a special
169  *              character, usually `%|-|%', although `%|+|%' is also used
170  *              sometimes.  As special exceptions, the word containing only a
171  *              `%|-|%' is considered to be a non-option, since it usually
172  *              represents standard input or output as a filename, and the
173  *              word containing a double-dash `%|--|%' is used to mark all
174  *              following words as being non-options regardless of their
175  *              initial character.
176  *
177  *              Traditionally, all words after the first non-option have been
178  *              considered to be non-options automatically, so that options
179  *              must be specified before filenames.  However, this
180  *              implementation can extract all the options from the command
181  *              line regardless of their position.  This can usually be
182  *              disabled by setting one of the environment variables
183  *              `%|POSIXLY_CORRECT|%' or `%|_POSIX_OPTION_ORDER|%'.
184  *
185  *              There are two different styles of options: `short' and
186  *              `long'.
187  *
188  *              Short options are the sort which Unix has known for ages: an
189  *              option is a single letter, preceded by a `%|-|%'.  Short
190  *              options can be joined together to save space (and possibly to
191  *              make silly words): e.g., instead of giving options
192  *              `%|-x.-y|%', a user could write `%|-xy|%'.  Some short
193  *              options can have arguments, which appear after the option
194  *              letter, either immediately following, or in the next `word'
195  *              (so an option with an argument could be written as
196  *              `%|-o foo|%' or as `%|-ofoo|%').  Note that options with
197  *              optional arguments must be written in the second style.
198  *
199  *              When a short option controls a flag setting, it is sometimes
200  *              possible to explicitly turn the flag off, as well as turning
201  *              it on, (usually to override default options).  This is
202  *              usually done by using a `%|+|%' instead of a `%|-|%' to
203  *              introduce the option.
204  *
205  *              Long options, as popularized by the GNU utilities, are given
206  *              long-ish memorable names, preceded by a double-dash `%|--|%'.
207  *              Since their names are more than a single character, long
208  *              options can't be combined in the same way as short options.
209  *              Arguments to long options may be given either in the same
210  *              `word', separated from the option name by an equals sign, or
211  *              in the following `word'.
212  *
213  *              Long option names can be abbreviated if necessary, as long
214  *              as the abbreviation is unique.  This means that options can
215  *              have sensible and memorable names but still not require much
216  *              typing from an experienced user.
217  *
218  *              Like short options, long options can control flag settings.
219  *              The options to manipulate these settings come in pairs: an
220  *              option of the form `%|--set-flag|%' might set the flag, while
221  *              an option of the form `%|--no-set-flag|%' might clear it.
222  *
223  *              It is usual for applications to provide both short and long
224  *              options with identical behaviour.  Some applications with
225  *              lots of options may only provide long options (although they
226  *              will often be only two or three characters long).  In this
227  *              case, long options can be preceded with a single `%|-|%'
228  *              character, and negated by a `%|+|%' character.
229  *
230  *              Finally, some (older) programs accept arguments of the form
231  *              `%%@.{"-"<number>}%%', to set some numerical parameter,
232  *              typically a line count of some kind.
233  *
234  *
235  *          How programs parse options
236  *
237  *              An application parses its options by calling mdwopt
238  *              repeatedly.  Each time it is called, mdwopt returns a value
239  *              describing the option just read, and stores information about
240  *              the option in a data block.  The value %$-1$% is returned
241  *              when there are no more options to be read.  The `%|?|%'
242  *              character is returned when an error is encountered.
243  *
244  *              Before starting to parse options, the value @data->ind@ must
245  *              be set to 0 or 1. The value of @data->err@ can also be set,
246  *              to choose whether errors are reported by mdwopt.
247  *
248  *              The program's `@argc@' and `@argv@' arguments are passed to
249  *              the options parser, so that it can read the command line.  A
250  *              flags word is also passed, allowing the program fine control
251  *              over parsing.  The flags are described above.
252  *
253  *              Short options are described by a string, which once upon a
254  *              time just contained the permitted option characters.  Now the
255  *              options string begins with a collection of flag characters,
256  *              and various flag characters can be put after options
257  *              characters to change their properties.
258  *
259  *              If the first character of the short options string is
260  *              `%|+|%', `%|-|%' or `%|!|%', the order in which options are
261  *              read is modified, as follows:
262  *
263  *              `%|+|%' forces the POSIX order to be used. As soon as a non-
264  *                      option is found, mdwopt returns %$-1$%.
265  *
266  *              `%|-|%' makes mdwopt treat non-options as being `special'
267  *                      sorts of option. When a non-option word is found, the
268  *                      value 0 is returned, and the actual text of the word
269  *                      is stored as being the option's argument.
270  *
271  *              `%|!|%' forces the default order to be used.  The entire
272  *                      command line is scanned for options, which are
273  *                      returned in order.  However, during this process,
274  *                      the options are moved in the @argv@ array, so that
275  *                      they appear before the non- options.
276  *
277  *              A `%|:|%' character may be placed after the ordering flag (or
278  *              at the very beginning if no ordering flag is given) which
279  *              indicates that the character `%|:|%', rather than `%|?|%',
280  *              should be returned if a missing argument error is detected.
281  *
282  *              Each option in the string can be followed by a `%|+|%' sign,
283  *              indicating that it can be negated, a `%|:|%' sign indicating
284  *              that it requires an argument, or a `%|::|%' string,
285  *              indicating an optional argument.  Both `%|+|%' and `%|:|%' or
286  *              `%|::|%' may be given, although the `%|+|%' must come first.
287  *
288  *              If an option is found, the option character is returned to
289  *              the caller.  A pointer to an argument is stored in
290  *              @data->arg@, or @NULL@ is stored if there was no argument.
291  *              If a negated option was found, the option character is
292  *              returned ORred with @OPTF_NEGATED@ (bit 8 set).
293  *
294  *              Long options are described in a table.  Each entry in the
295  *              table is of type @struct option@, and the table is terminated
296  *              by an entry whose @name@ field is null.  Each option has
297  *              a flags word which, due to historical reasons, is called
298  *              @has_arg@.  This describes various properties of the option,
299  *              such as what sort of argument it takes, and whether it can
300  *              be negated.
301  *
302  *              When mdwopt finds a long option, it looks the name up in the
303  *              table. The index of the matching entry is stored in the
304  *              @longind@ variable, passed to mdwopt (unless @longind@ is 0):
305  *              a value of %$-1$% indicates that no long option was
306  *              found. The behaviour is then dependent on the values in the
307  *              table entry.  If @flag@ is nonzero, it points to an integer
308  *              to be modified by mdwopt.  Usually the value in the @val@
309  *              field is simply stored in the @flag@ variable. If the flag
310  *              @OPTF_SWITCH@ is set, however, the value is combined with
311  *              the existing value of the flags using a bitwise OR.  If
312  *              @OPTF_NEGATE@ is set, then the flag bit will be cleared if a
313  *              matching negated long option is found.  The value 0 is
314  *              returned.
315  *
316  *              If @flag@ is zero, the value in @val@ is returned by mdwopt,
317  *              possibly with bit 8 set if the option was negated.
318  *
319  *              Arguments for long options are stored in @data->arg@, as
320  *              before.
321  *
322  *              Numeric options, if enabled, cause the value `%|#|%' to be
323  *              returned, and the numeric value to be stored in @data->opt@.
324  *
325  *              If the flag @OPTF_ENVVAR@ is set on entry, options will be
326  *              extracted from an environment variable whose name is built by
327  *              capitalizing all the letters of the program's name.  (This
328  *              allows a user to have different default settings for a
329  *              program, by calling it through different symbolic links.)
330  */
331
332 extern int mdwopt(int /*argc*/, char *const */*argv*/,
333                   const char */*shortopt*/,
334                   const struct option */*longopts*/, int */*longind*/,
335                   mdwopt_data */*data*/, int /*flags*/);
336
337 /* --- Macros for more commonly used routines --- */
338
339 #define getopt(c, v, o) mdwopt(c, v, o, 0, 0, 0, OPTF_NOLONGS)
340 #define getopt_long(c, v, o, l, li) mdwopt(c, v, o, l, li, 0, 0)
341 #define getopt_long_only(c, v, o, l, li)                                \
342   mdwopt(c, v, o, l, li, 0, OPTF_NOSHORTS)
343
344 #ifdef __cplusplus
345 }
346 #endif
347
348 /*----- C++ wrapper class -------------------------------------------------*/
349
350 #ifdef __cplusplus
351
352 /* --- Class: @MdwOpt@ --- *
353  *
354  * Parent:      ---
355  *
356  * Methods:     @MdwOpt@ -- construct a new mdwopt object with the given
357  *                      arguments.  These are remembered for later use.
358  *              @arg@ -- return the argument of the current option
359  *                      arguments.  These are remembered for later use.
360  *              @arg@ -- return the argument of the current option
361  *              @opt@ -- return the value of the current option
362  *              @ind@ -- return the index of the next unread argument
363  *              @longind@ -- return index of current long option in table
364  *              @errors@ -- return or set whether we report errors to the
365  *                      user
366  *              @prog@ -- return program name from @argv[0]@
367  *              @next@ -- return next option read from the table
368  *
369  * Use:         A simple C++ class for encapsulating the options parser.
370  *              The methods are all nice and simple, and extremely similar
371  *              to the normal C interface described above.
372  */
373
374 class MdwOpt {
375   protected:
376     int argc;
377     char * const *argv;
378     const char *shortopts;
379     const struct option *longopts;
380     int long_ind;
381     int flags;
382
383     mdwopt_data data;
384
385   public:
386     MdwOpt(int c, char * const *v, const char *so,
387            const struct option *lo, int f=0) :
388       argc(c), argv(v), shortopts(so), longopts(lo), flags(f) {
389         data.ind = 0;
390         data.err = 1;
391     }
392
393     const char *arg(void) const { return (data.arg); }
394     int opt(void) const { return (data.opt); }
395     int errors(void) const { return (data.err); }
396     int errors(int e) { int oe = data.err; data.err = e; return (oe); }
397     int ind(void) const { return (data.ind); }
398     int longind(void) const { return (long_ind); }
399     const char *prog(void) const { return (data.prog); }
400
401     int next(void) {
402       return (mdwopt(argc, argv, shortopts,
403                      longopts, &long_ind, &data, flags));
404     }
405 };
406
407 #endif
408
409 /*----- That's all, folks -------------------------------------------------*/
410
411 #endif