1 /* $NetBSD: scanopt.c,v 1.1.1.1 2009/10/26 00:26:56 christos Exp $ */
3 /* flex - tool to generate fast lexical analyzers */
5 /* Copyright (c) 1990 The Regents of the University of California. */
6 /* All rights reserved. */
8 /* This code is derived from software contributed to Berkeley by */
11 /* The United States Government has rights in this work pursuant */
12 /* to contract no. DE-AC03-76SF00098 between the United States */
13 /* Department of Energy and the University of California. */
15 /* This file is part of flex. */
17 /* Redistribution and use in source and binary forms, with or without */
18 /* modification, are permitted provided that the following conditions */
21 /* 1. Redistributions of source code must retain the above copyright */
22 /* notice, this list of conditions and the following disclaimer. */
23 /* 2. Redistributions in binary form must reproduce the above copyright */
24 /* notice, this list of conditions and the following disclaimer in the */
25 /* documentation and/or other materials provided with the distribution. */
27 /* Neither the name of the University nor the names of its contributors */
28 /* may be used to endorse or promote products derived from this software */
29 /* without specific prior written permission. */
31 /* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR */
32 /* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED */
33 /* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR */
40 /* Internal structures */
42 #ifdef HAVE_STRCASECMP
43 #define STRCASECMP(a,b) strcasecmp(a,b)
45 static int STRCASECMP
PROTO ((const char *, const char *));
47 static int STRCASECMP (a
, b
)
51 while (tolower ((unsigned char)*a
++) == tolower ((unsigned char)*b
++)) ;
62 int flags
; /* The above hex flags. */
63 int namelen
; /* Length of the actual option word, e.g., "--file[=foo]" is 4 */
64 int printlen
; /* Length of entire string, e.g., "--file[=foo]" is 12 */
69 const optspec_t
*options
; /* List of options. */
70 struct _aux
*aux
; /* Auxiliary data about options. */
71 int optc
; /* Number of options. */
72 int argc
; /* Number of args. */
73 char **argv
; /* Array of strings. */
74 int index
; /* Used as: argv[index][subscript]. */
76 char no_err_msg
; /* If true, do not print errors. */
81 /* Accessor functions. These WOULD be one-liners, but portability calls. */
82 static const char *NAME
PROTO ((struct _scanopt_t
*, int));
83 static int PRINTLEN
PROTO ((struct _scanopt_t
*, int));
84 static int RVAL
PROTO ((struct _scanopt_t
*, int));
85 static int FLAGS
PROTO ((struct _scanopt_t
*, int));
86 static const char *DESC
PROTO ((struct _scanopt_t
*, int));
87 static int scanopt_err
PROTO ((struct _scanopt_t
*, int, int, int));
88 static int matchlongopt
PROTO ((char *, char **, int *, char **, int *));
90 PROTO ((struct _scanopt_t
*, int, char *, int, int *, int *opt_offset
));
92 static const char *NAME (s
, i
)
96 return s
->options
[i
].opt_fmt
+
97 ((s
->aux
[i
].flags
& IS_LONG
) ? 2 : 1);
100 static int PRINTLEN (s
, i
)
101 struct _scanopt_t
*s
;
104 return s
->aux
[i
].printlen
;
107 static int RVAL (s
, i
)
108 struct _scanopt_t
*s
;
111 return s
->options
[i
].r_val
;
114 static int FLAGS (s
, i
)
115 struct _scanopt_t
*s
;
118 return s
->aux
[i
].flags
;
121 static const char *DESC (s
, i
)
122 struct _scanopt_t
*s
;
125 return s
->options
[i
].desc
? s
->options
[i
].desc
: "";
128 #ifndef NO_SCANOPT_USAGE
129 static int get_cols
PROTO ((void));
131 static int get_cols ()
134 int cols
= 80; /* default */
136 #ifdef HAVE_NCURSES_H
143 if ((env
= getenv ("COLUMNS")) != NULL
)
150 /* Macro to check for NULL before assigning a value. */
151 #define SAFE_ASSIGN(ptr,val) \
157 /* Macro to assure we reset subscript whenever we adjust s->index.*/
158 #define INC_INDEX(s,n) \
164 scanopt_t
*scanopt_init (options
, argc
, argv
, flags
)
165 const optspec_t
*options
;
171 struct _scanopt_t
*s
;
172 s
= (struct _scanopt_t
*) malloc (sizeof (struct _scanopt_t
));
174 s
->options
= options
;
177 s
->argv
= (char **) argv
;
180 s
->no_err_msg
= (flags
& SCANOPT_NO_ERR_MSG
);
184 /* Determine option count. (Find entry with all zeros). */
186 while (options
[s
->optc
].opt_fmt
187 || options
[s
->optc
].r_val
|| options
[s
->optc
].desc
)
190 /* Build auxiliary data */
191 s
->aux
= (struct _aux
*) malloc (s
->optc
* sizeof (struct _aux
));
193 for (i
= 0; i
< s
->optc
; i
++) {
194 const char *p
, *pname
;
195 const struct optspec_t
*opt
;
198 opt
= s
->options
+ i
;
201 aux
->flags
= ARG_NONE
;
203 if (opt
->opt_fmt
[0] == '-' && opt
->opt_fmt
[1] == '-') {
204 aux
->flags
|= IS_LONG
;
205 pname
= opt
->opt_fmt
+ 2;
209 pname
= opt
->opt_fmt
+ 1;
212 aux
->printlen
= strlen (opt
->opt_fmt
);
215 for (p
= pname
+ 1; *p
; p
++) {
216 /* detect required arg */
217 if (*p
== '=' || isspace ((unsigned char)*p
)
218 || !(aux
->flags
& IS_LONG
)) {
219 if (aux
->namelen
== 0)
220 aux
->namelen
= p
- pname
;
221 aux
->flags
|= ARG_REQ
;
222 aux
->flags
&= ~ARG_NONE
;
224 /* detect optional arg. This overrides required arg. */
226 if (aux
->namelen
== 0)
227 aux
->namelen
= p
- pname
;
228 aux
->flags
&= ~(ARG_REQ
| ARG_NONE
);
229 aux
->flags
|= ARG_OPT
;
233 if (aux
->namelen
== 0)
234 aux
->namelen
= p
- pname
;
236 return (scanopt_t
*) s
;
239 #ifndef NO_SCANOPT_USAGE
240 /* these structs are for scanopt_usage(). */
243 struct usg_elem
*next
;
244 struct usg_elem
*alias
;
246 typedef struct usg_elem usg_elem
;
249 /* Prints a usage message based on contents of optlist.
251 * scanner - The scanner, already initialized with scanopt_init().
252 * fp - The file stream to write to.
253 * usage - Text to be prepended to option list.
254 * Return: Always returns 0 (zero).
255 * The output looks something like this:
257 [indent][option, alias1, alias2...][indent][description line1
258 description line2...]
260 int scanopt_usage (scanner
, fp
, usage
)
265 struct _scanopt_t
*s
;
266 int i
, columns
, indent
= 2;
267 usg_elem
*byr_val
= NULL
; /* option indices sorted by r_val */
268 usg_elem
*store
; /* array of preallocated elements. */
278 s
= (struct _scanopt_t
*) scanner
;
281 fprintf (fp
, "%s\n", usage
);
284 /* Find the basename of argv[0] */
287 p
= s
->argv
[0] + strlen (s
->argv
[0]);
288 while (p
!= s
->argv
[0] && *p
!= '/')
293 fprintf (fp
, _("Usage: %s [OPTIONS]...\n"), p
);
297 /* Sort by r_val and string. Yes, this is O(n*n), but n is small. */
298 store
= (usg_elem
*) malloc (s
->optc
* sizeof (usg_elem
));
299 for (i
= 0; i
< s
->optc
; i
++) {
301 /* grab the next preallocate node. */
302 ue
= store
+ store_idx
++;
304 ue
->next
= ue
->alias
= NULL
;
306 /* insert into list. */
311 usg_elem
**ue_curr
, **ptr_if_no_alias
= NULL
;
315 if (RVAL (s
, (*ue_curr
)->idx
) ==
317 /* push onto the alias list. */
318 ue_curr
= &((*ue_curr
)->alias
);
324 STRCASECMP (NAME (s
, (*ue_curr
)->idx
),
325 NAME (s
, ue
->idx
)) > 0) {
326 ptr_if_no_alias
= ue_curr
;
328 ue_curr
= &((*ue_curr
)->next
);
330 if (!found_alias
&& ptr_if_no_alias
)
331 ue_curr
= ptr_if_no_alias
;
339 printf ("ORIGINAL:\n");
340 for (i
= 0; i
< s
->optc
; i
++)
341 printf ("%2d: %s\n", i
, NAME (s
, i
));
342 printf ("SORTED:\n");
347 printf ("%2d: %s\n", ue
->idx
, NAME (s
, ue
->idx
));
348 for (ue2
= ue
->alias
; ue2
; ue2
= ue2
->next
)
349 printf (" +---> %2d: %s\n", ue2
->idx
,
356 /* Now build each row of output. */
358 /* first pass calculate how much room we need. */
359 for (ue
= byr_val
; ue
; ue
= ue
->next
) {
362 int nshort
= 0, nlong
= 0;
365 #define CALC_LEN(i) do {\
366 if(FLAGS(s,i) & IS_LONG) \
367 len += (nlong++||nshort) ? 2+PRINTLEN(s,i) : PRINTLEN(s,i);\
369 len += (nshort++||nlong)? 2+PRINTLEN(s,i) : PRINTLEN(s,i);\
372 if (!(FLAGS (s
, ue
->idx
) & IS_LONG
))
375 /* do short aliases first. */
376 for (ap
= ue
->alias
; ap
; ap
= ap
->next
) {
377 if (FLAGS (s
, ap
->idx
) & IS_LONG
)
382 if (FLAGS (s
, ue
->idx
) & IS_LONG
)
385 /* repeat the above loop, this time for long aliases. */
386 for (ap
= ue
->alias
; ap
; ap
= ap
->next
) {
387 if (!(FLAGS (s
, ap
->idx
) & IS_LONG
))
395 /* It's much easier to calculate length for description column! */
396 len
= strlen (DESC (s
, ue
->idx
));
401 /* Determine how much room we have, and how much we will allocate to each col.
402 * Do not address pathological cases. Output will just be ugly. */
403 columns
= get_cols () - 1;
404 if (maxlen
[0] + maxlen
[1] + indent
* 2 > columns
) {
405 /* col 0 gets whatever it wants. we'll wrap the desc col. */
406 maxlen
[1] = columns
- (maxlen
[0] + indent
* 2);
407 if (maxlen
[1] < 14) /* 14 is arbitrary lower limit on desc width. */
410 desccol
= maxlen
[0] + indent
* 2;
412 #define PRINT_SPACES(fp,n)\
421 /* Second pass (same as above loop), this time we print. */
422 /* Sloppy hack: We iterate twice. The first time we print short and long options.
423 The second time we print those lines that have ONLY long options. */
424 while (print_run
++ < 2) {
425 for (ue
= byr_val
; ue
; ue
= ue
->next
) {
427 int nwords
= 0, nchars
= 0, has_short
= 0;
429 /* TODO: get has_short schtick to work */
430 has_short
= !(FLAGS (s
, ue
->idx
) & IS_LONG
);
431 for (ap
= ue
->alias
; ap
; ap
= ap
->next
) {
432 if (!(FLAGS (s
, ap
->idx
) & IS_LONG
)) {
437 if ((print_run
== 1 && !has_short
) ||
438 (print_run
== 2 && has_short
))
441 PRINT_SPACES (fp
, indent
);
444 /* Print, adding a ", " between aliases. */
445 #define PRINT_IT(i) do{\
447 nchars+=fprintf(fp,", ");\
448 nchars+=fprintf(fp,"%s",s->options[i].opt_fmt);\
451 if (!(FLAGS (s
, ue
->idx
) & IS_LONG
))
454 /* print short aliases first. */
455 for (ap
= ue
->alias
; ap
; ap
= ap
->next
) {
456 if (!(FLAGS (s
, ap
->idx
) & IS_LONG
))
461 if (FLAGS (s
, ue
->idx
) & IS_LONG
)
464 /* repeat the above loop, this time for long aliases. */
465 for (ap
= ue
->alias
; ap
; ap
= ap
->next
) {
466 if (FLAGS (s
, ap
->idx
) & IS_LONG
)
471 PRINT_SPACES (fp
, desccol
- nchars
);
473 /* Print description, wrapped to maxlen[1] columns. */
477 pstart
= DESC (s
, ue
->idx
);
480 const char *lastws
= NULL
, *p
;
484 while (*p
&& n
< maxlen
[1]
486 if (isspace ((unsigned char)*p
)
487 || *p
== '-') lastws
=
493 if (!*p
) { /* hit end of desc. done. */
498 else if (*p
== '\n') { /* print everything up to here then wrap. */
499 fprintf (fp
, "%.*s\n", n
,
501 PRINT_SPACES (fp
, desccol
);
505 else { /* we hit the edge of the screen. wrap at space if possible. */
522 PRINT_SPACES (fp
, desccol
);
532 #endif /* no scanopt_usage */
535 static int scanopt_err (s
, opt_offset
, is_short
, err
)
536 struct _scanopt_t
*s
;
541 const char *optname
= "";
543 const optspec_t
*opt
= NULL
;
546 opt
= s
->options
+ opt_offset
;
548 if (!s
->no_err_msg
) {
550 if (s
->index
> 0 && s
->index
< s
->argc
) {
553 s
->argv
[s
->index
][s
->subscript
];
558 optname
= s
->argv
[s
->index
];
562 fprintf (stderr
, "%s: ", s
->argv
[0]);
564 case SCANOPT_ERR_ARG_NOT_ALLOWED
:
567 ("option `%s' doesn't allow an argument\n"),
570 case SCANOPT_ERR_ARG_NOT_FOUND
:
572 _("option `%s' requires an argument\n"),
575 case SCANOPT_ERR_OPT_AMBIGUOUS
:
576 fprintf (stderr
, _("option `%s' is ambiguous\n"),
579 case SCANOPT_ERR_OPT_UNRECOGNIZED
:
580 fprintf (stderr
, _("Unrecognized option `%s'\n"),
584 fprintf (stderr
, _("Unknown error=(%d)\n"), err
);
592 /* Internal. Match str against the regex ^--([^=]+)(=(.*))?
593 * return 1 if *looks* like a long option.
594 * 'str' is the only input argument, the rest of the arguments are output only.
595 * optname will point to str + 2
598 static int matchlongopt (str
, optname
, optlen
, arg
, arglen
)
607 *optname
= *arg
= (char *) 0;
608 *optlen
= *arglen
= 0;
610 /* Match regex /--./ */
612 if (p
[0] != '-' || p
[1] != '-' || !p
[2])
616 *optname
= (char *) p
;
618 /* find the end of optname */
619 while (*p
&& *p
!= '=')
622 *optlen
= p
- *optname
;
625 /* an option with no '=...' part. */
629 /* We saw an '=' char. The rest of p is the arg. */
640 /* Internal. Look up long or short option by name.
641 * Long options must match a non-ambiguous prefix, or exact match.
642 * Short options must be exact.
643 * Return boolean true if found and no error.
644 * Error stored in err_code or zero if no error. */
645 static int find_opt (s
, lookup_long
, optstart
, len
, err_code
, opt_offset
)
646 struct _scanopt_t
*s
;
653 int nmatch
= 0, lastr_val
= 0, i
;
661 for (i
= 0; i
< s
->optc
; i
++) {
665 (char *) (s
->options
[i
].opt_fmt
+
666 (lookup_long
? 2 : 1));
668 if (lookup_long
&& (s
->aux
[i
].flags
& IS_LONG
)) {
669 if (len
> s
->aux
[i
].namelen
)
672 if (strncmp (optname
, optstart
, len
) == 0) {
676 /* exact match overrides all. */
677 if (len
== s
->aux
[i
].namelen
) {
682 /* ambiguity is ok between aliases. */
685 s
->options
[i
].r_val
) nmatch
--;
686 lastr_val
= s
->options
[i
].r_val
;
689 else if (!lookup_long
&& !(s
->aux
[i
].flags
& IS_LONG
)) {
690 if (optname
[0] == optstart
[0]) {
698 *err_code
= SCANOPT_ERR_OPT_UNRECOGNIZED
;
701 else if (nmatch
> 1) {
702 *err_code
= SCANOPT_ERR_OPT_AMBIGUOUS
;
706 return *err_code
? 0 : 1;
710 int scanopt (svoid
, arg
, optindex
)
715 char *optname
= NULL
, *optarg
= NULL
, *pstart
;
716 int namelen
= 0, arglen
= 0;
717 int errcode
= 0, has_next
;
718 const optspec_t
*optp
;
719 struct _scanopt_t
*s
;
724 s
= (struct _scanopt_t
*) svoid
;
726 /* Normalize return-parameters. */
727 SAFE_ASSIGN (arg
, NULL
);
728 SAFE_ASSIGN (optindex
, s
->index
);
730 if (s
->index
>= s
->argc
)
733 /* pstart always points to the start of our current scan. */
734 pstart
= s
->argv
[s
->index
] + s
->subscript
;
738 if (s
->subscript
== 0) {
740 /* test for exact match of "--" */
741 if (pstart
[0] == '-' && pstart
[1] == '-' && !pstart
[2]) {
742 SAFE_ASSIGN (optindex
, s
->index
+ 1);
749 (pstart
, &optname
, &namelen
, &optarg
, &arglen
)) {
751 /* it LOOKS like an opt, but is it one?! */
753 (s
, 1, optname
, namelen
, &errcode
,
755 scanopt_err (s
, opt_offset
, 0, errcode
);
758 /* We handle this below. */
761 /* Check for short opt. */
763 else if (pstart
[0] == '-' && pstart
[1]) {
764 /* Pass through to below. */
771 /* It's not an option. We're done. */
776 /* We have to re-check the subscript status because it
777 * may have changed above. */
779 if (s
->subscript
!= 0) {
781 /* we are somewhere in a run of short opts,
782 * e.g., at the 'z' in `tar -xzf` */
789 (s
, 0, pstart
, namelen
, &errcode
, &opt_offset
)) {
790 return scanopt_err (s
, opt_offset
, 1, errcode
);
799 arglen
= strlen (optarg
);
802 /* At this point, we have a long or short option matched at opt_offset into
803 * the s->options array (and corresponding aux array).
804 * A trailing argument is in {optarg,arglen}, if any.
807 /* Look ahead in argv[] to see if there is something
808 * that we can use as an argument (if needed). */
809 has_next
= s
->index
+ 1 < s
->argc
810 && strcmp ("--", s
->argv
[s
->index
+ 1]) != 0;
812 optp
= s
->options
+ opt_offset
;
813 auxp
= s
->aux
+ opt_offset
;
815 /* case: no args allowed */
816 if (auxp
->flags
& ARG_NONE
) {
817 if (optarg
&& !is_short
) {
818 scanopt_err (s
, opt_offset
, is_short
, errcode
=
819 SCANOPT_ERR_ARG_NOT_ALLOWED
);
831 if (auxp
->flags
& ARG_REQ
) {
832 if (!optarg
&& !has_next
)
833 return scanopt_err (s
, opt_offset
, is_short
,
834 SCANOPT_ERR_ARG_NOT_FOUND
);
837 /* Let the next argv element become the argument. */
838 SAFE_ASSIGN (arg
, s
->argv
[s
->index
+ 1]);
842 SAFE_ASSIGN (arg
, (char *) optarg
);
849 if (auxp
->flags
& ARG_OPT
) {
850 SAFE_ASSIGN (arg
, optarg
);
856 /* Should not reach here. */
861 int scanopt_destroy (svoid
)
864 struct _scanopt_t
*s
;
866 s
= (struct _scanopt_t
*) svoid
;
876 /* vim:set tabstop=8 softtabstop=4 shiftwidth=4: */