1 /* flex - tool to generate fast lexical analyzers */
3 /* Copyright (c) 1990 The Regents of the University of California. */
4 /* All rights reserved. */
6 /* This code is derived from software contributed to Berkeley by */
9 /* The United States Government has rights in this work pursuant */
10 /* to contract no. DE-AC03-76SF00098 between the United States */
11 /* Department of Energy and the University of California. */
13 /* This file is part of flex. */
15 /* Redistribution and use in source and binary forms, with or without */
16 /* modification, are permitted provided that the following conditions */
19 /* 1. Redistributions of source code must retain the above copyright */
20 /* notice, this list of conditions and the following disclaimer. */
21 /* 2. Redistributions in binary form must reproduce the above copyright */
22 /* notice, this list of conditions and the following disclaimer in the */
23 /* documentation and/or other materials provided with the distribution. */
25 /* Neither the name of the University nor the names of its contributors */
26 /* may be used to endorse or promote products derived from this software */
27 /* without specific prior written permission. */
29 /* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR */
30 /* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED */
31 /* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR */
38 /* Internal structures */
40 #ifdef HAVE_STRCASECMP
41 #define STRCASECMP(a,b) strcasecmp(a,b)
43 static int STRCASECMP PROTO ((const char *, const char *));
45 static int STRCASECMP (a, b)
49 while (tolower (*a++) == tolower (*b++)) ;
60 int flags; /* The above hex flags. */
61 int namelen; /* Length of the actual option word, e.g., "--file[=foo]" is 4 */
62 int printlen; /* Length of entire string, e.g., "--file[=foo]" is 12 */
67 const optspec_t *options; /* List of options. */
68 struct _aux *aux; /* Auxiliary data about options. */
69 int optc; /* Number of options. */
70 int argc; /* Number of args. */
71 char **argv; /* Array of strings. */
72 int index; /* Used as: argv[index][subscript]. */
74 char no_err_msg; /* If true, do not print errors. */
79 /* Accessor functions. These WOULD be one-liners, but portability calls. */
80 static const char *NAME PROTO ((struct _scanopt_t *, int));
81 static int PRINTLEN PROTO ((struct _scanopt_t *, int));
82 static int RVAL PROTO ((struct _scanopt_t *, int));
83 static int FLAGS PROTO ((struct _scanopt_t *, int));
84 static const char *DESC PROTO ((struct _scanopt_t *, int));
85 static int scanopt_err PROTO ((struct _scanopt_t *, int, int, int));
86 static int matchlongopt PROTO ((char *, char **, int *, char **, int *));
88 PROTO ((struct _scanopt_t *, int, char *, int, int *, int *opt_offset));
90 static const char *NAME (s, i)
94 return s->options[i].opt_fmt +
95 ((s->aux[i].flags & IS_LONG) ? 2 : 1);
98 static int PRINTLEN (s, i)
102 return s->aux[i].printlen;
105 static int RVAL (s, i)
106 struct _scanopt_t *s;
109 return s->options[i].r_val;
112 static int FLAGS (s, i)
113 struct _scanopt_t *s;
116 return s->aux[i].flags;
119 static const char *DESC (s, i)
120 struct _scanopt_t *s;
123 return s->options[i].desc ? s->options[i].desc : "";
126 #ifndef NO_SCANOPT_USAGE
127 static int get_cols PROTO ((void));
129 static int get_cols ()
132 int cols = 80; /* default */
134 #ifdef HAVE_NCURSES_H
141 if ((env = getenv ("COLUMNS")) != NULL)
148 /* Macro to check for NULL before assigning a value. */
149 #define SAFE_ASSIGN(ptr,val) \
155 /* Macro to assure we reset subscript whenever we adjust s->index.*/
156 #define INC_INDEX(s,n) \
162 scanopt_t *scanopt_init (options, argc, argv, flags)
163 const optspec_t *options;
169 struct _scanopt_t *s;
170 s = (struct _scanopt_t *) malloc (sizeof (struct _scanopt_t));
172 s->options = options;
175 s->argv = (char **) argv;
178 s->no_err_msg = (flags & SCANOPT_NO_ERR_MSG);
182 /* Determine option count. (Find entry with all zeros). */
184 while (options[s->optc].opt_fmt
185 || options[s->optc].r_val || options[s->optc].desc)
188 /* Build auxiliary data */
189 s->aux = (struct _aux *) malloc (s->optc * sizeof (struct _aux));
191 for (i = 0; i < s->optc; i++) {
192 const Char *p, *pname;
193 const struct optspec_t *opt;
196 opt = s->options + i;
199 aux->flags = ARG_NONE;
201 if (opt->opt_fmt[0] == '-' && opt->opt_fmt[1] == '-') {
202 aux->flags |= IS_LONG;
203 pname = (const Char *)(opt->opt_fmt + 2);
207 pname = (const Char *)(opt->opt_fmt + 1);
210 aux->printlen = strlen (opt->opt_fmt);
213 for (p = pname + 1; *p; p++) {
214 /* detect required arg */
215 if (*p == '=' || isspace (*p)
216 || !(aux->flags & IS_LONG)) {
217 if (aux->namelen == 0)
218 aux->namelen = p - pname;
219 aux->flags |= ARG_REQ;
220 aux->flags &= ~ARG_NONE;
222 /* detect optional arg. This overrides required arg. */
224 if (aux->namelen == 0)
225 aux->namelen = p - pname;
226 aux->flags &= ~(ARG_REQ | ARG_NONE);
227 aux->flags |= ARG_OPT;
231 if (aux->namelen == 0)
232 aux->namelen = p - pname;
234 return (scanopt_t *) s;
237 #ifndef NO_SCANOPT_USAGE
238 /* these structs are for scanopt_usage(). */
241 struct usg_elem *next;
242 struct usg_elem *alias;
244 typedef struct usg_elem usg_elem;
247 /* Prints a usage message based on contents of optlist.
249 * scanner - The scanner, already initialized with scanopt_init().
250 * fp - The file stream to write to.
251 * usage - Text to be prepended to option list.
252 * Return: Always returns 0 (zero).
253 * The output looks something like this:
255 [indent][option, alias1, alias2...][indent][description line1
256 description line2...]
258 int scanopt_usage (scanner, fp, usage)
263 struct _scanopt_t *s;
264 int i, columns, indent = 2;
265 usg_elem *byr_val = NULL; /* option indices sorted by r_val */
266 usg_elem *store; /* array of preallocated elements. */
276 s = (struct _scanopt_t *) scanner;
279 fprintf (fp, "%s\n", usage);
282 /* Find the basename of argv[0] */
285 p = s->argv[0] + strlen (s->argv[0]);
286 while (p != s->argv[0] && *p != '/')
291 fprintf (fp, _("Usage: %s [OPTIONS]...\n"), p);
295 /* Sort by r_val and string. Yes, this is O(n*n), but n is small. */
296 store = (usg_elem *) malloc (s->optc * sizeof (usg_elem));
297 for (i = 0; i < s->optc; i++) {
299 /* grab the next preallocate node. */
300 ue = store + store_idx++;
302 ue->next = ue->alias = NULL;
304 /* insert into list. */
309 usg_elem **ue_curr, **ptr_if_no_alias = NULL;
313 if (RVAL (s, (*ue_curr)->idx) ==
315 /* push onto the alias list. */
316 ue_curr = &((*ue_curr)->alias);
322 STRCASECMP (NAME (s, (*ue_curr)->idx),
323 NAME (s, ue->idx)) > 0) {
324 ptr_if_no_alias = ue_curr;
326 ue_curr = &((*ue_curr)->next);
328 if (!found_alias && ptr_if_no_alias)
329 ue_curr = ptr_if_no_alias;
337 printf ("ORIGINAL:\n");
338 for (i = 0; i < s->optc; i++)
339 printf ("%2d: %s\n", i, NAME (s, i));
340 printf ("SORTED:\n");
345 printf ("%2d: %s\n", ue->idx, NAME (s, ue->idx));
346 for (ue2 = ue->alias; ue2; ue2 = ue2->next)
347 printf (" +---> %2d: %s\n", ue2->idx,
354 /* Now build each row of output. */
356 /* first pass calculate how much room we need. */
357 for (ue = byr_val; ue; ue = ue->next) {
360 int nshort = 0, nlong = 0;
363 #define CALC_LEN(i) do {\
364 if(FLAGS(s,i) & IS_LONG) \
365 len += (nlong++||nshort) ? 2+PRINTLEN(s,i) : PRINTLEN(s,i);\
367 len += (nshort++||nlong)? 2+PRINTLEN(s,i) : PRINTLEN(s,i);\
370 if (!(FLAGS (s, ue->idx) & IS_LONG))
373 /* do short aliases first. */
374 for (ap = ue->alias; ap; ap = ap->next) {
375 if (FLAGS (s, ap->idx) & IS_LONG)
380 if (FLAGS (s, ue->idx) & IS_LONG)
383 /* repeat the above loop, this time for long aliases. */
384 for (ap = ue->alias; ap; ap = ap->next) {
385 if (!(FLAGS (s, ap->idx) & IS_LONG))
393 /* It's much easier to calculate length for description column! */
394 len = strlen (DESC (s, ue->idx));
399 /* Determine how much room we have, and how much we will allocate to each col.
400 * Do not address pathological cases. Output will just be ugly. */
401 columns = get_cols () - 1;
402 if (maxlen[0] + maxlen[1] + indent * 2 > columns) {
403 /* col 0 gets whatever it wants. we'll wrap the desc col. */
404 maxlen[1] = columns - (maxlen[0] + indent * 2);
405 if (maxlen[1] < 14) /* 14 is arbitrary lower limit on desc width. */
408 desccol = maxlen[0] + indent * 2;
410 #define PRINT_SPACES(fp,n)\
419 /* Second pass (same as above loop), this time we print. */
420 /* Sloppy hack: We iterate twice. The first time we print short and long options.
421 The second time we print those lines that have ONLY long options. */
422 while (print_run++ < 2) {
423 for (ue = byr_val; ue; ue = ue->next) {
425 int nwords = 0, nchars = 0, has_short = 0;
427 /* TODO: get has_short schtick to work */
428 has_short = !(FLAGS (s, ue->idx) & IS_LONG);
429 for (ap = ue->alias; ap; ap = ap->next) {
430 if (!(FLAGS (s, ap->idx) & IS_LONG)) {
435 if ((print_run == 1 && !has_short) ||
436 (print_run == 2 && has_short))
439 PRINT_SPACES (fp, indent);
442 /* Print, adding a ", " between aliases. */
443 #define PRINT_IT(i) do{\
445 nchars+=fprintf(fp,", ");\
446 nchars+=fprintf(fp,"%s",s->options[i].opt_fmt);\
449 if (!(FLAGS (s, ue->idx) & IS_LONG))
452 /* print short aliases first. */
453 for (ap = ue->alias; ap; ap = ap->next) {
454 if (!(FLAGS (s, ap->idx) & IS_LONG))
459 if (FLAGS (s, ue->idx) & IS_LONG)
462 /* repeat the above loop, this time for long aliases. */
463 for (ap = ue->alias; ap; ap = ap->next) {
464 if (FLAGS (s, ap->idx) & IS_LONG)
469 PRINT_SPACES (fp, desccol - nchars);
471 /* Print description, wrapped to maxlen[1] columns. */
475 pstart = DESC (s, ue->idx);
478 const char *lastws = NULL, *p;
482 while (*p && n < maxlen[1]
484 if (isspace ((Char)(*p))
485 || *p == '-') lastws =
491 if (!*p) { /* hit end of desc. done. */
496 else if (*p == '\n') { /* print everything up to here then wrap. */
497 fprintf (fp, "%.*s\n", n,
499 PRINT_SPACES (fp, desccol);
503 else { /* we hit the edge of the screen. wrap at space if possible. */
507 (int)(lastws - pstart),
519 PRINT_SPACES (fp, desccol);
529 #endif /* no scanopt_usage */
532 static int scanopt_err (s, opt_offset, is_short, err)
533 struct _scanopt_t *s;
538 const char *optname = "";
540 const optspec_t *opt = NULL;
543 opt = s->options + opt_offset;
545 if (!s->no_err_msg) {
547 if (s->index > 0 && s->index < s->argc) {
550 s->argv[s->index][s->subscript];
555 optname = s->argv[s->index];
559 fprintf (stderr, "%s: ", s->argv[0]);
561 case SCANOPT_ERR_ARG_NOT_ALLOWED:
564 ("option `%s' doesn't allow an argument\n"),
567 case SCANOPT_ERR_ARG_NOT_FOUND:
569 _("option `%s' requires an argument\n"),
572 case SCANOPT_ERR_OPT_AMBIGUOUS:
573 fprintf (stderr, _("option `%s' is ambiguous\n"),
576 case SCANOPT_ERR_OPT_UNRECOGNIZED:
577 fprintf (stderr, _("Unrecognized option `%s'\n"),
581 fprintf (stderr, _("Unknown error=(%d)\n"), err);
589 /* Internal. Match str against the regex ^--([^=]+)(=(.*))?
590 * return 1 if *looks* like a long option.
591 * 'str' is the only input argument, the rest of the arguments are output only.
592 * optname will point to str + 2
595 static int matchlongopt (str, optname, optlen, arg, arglen)
604 *optname = *arg = (char *) 0;
605 *optlen = *arglen = 0;
607 /* Match regex /--./ */
609 if (p[0] != '-' || p[1] != '-' || !p[2])
613 *optname = (char *) p;
615 /* find the end of optname */
616 while (*p && *p != '=')
619 *optlen = p - *optname;
622 /* an option with no '=...' part. */
626 /* We saw an '=' char. The rest of p is the arg. */
637 /* Internal. Look up long or short option by name.
638 * Long options must match a non-ambiguous prefix, or exact match.
639 * Short options must be exact.
640 * Return boolean true if found and no error.
641 * Error stored in err_code or zero if no error. */
642 static int find_opt (s, lookup_long, optstart, len, err_code, opt_offset)
643 struct _scanopt_t *s;
650 int nmatch = 0, lastr_val = 0, i;
658 for (i = 0; i < s->optc; i++) {
662 (char *) (s->options[i].opt_fmt +
663 (lookup_long ? 2 : 1));
665 if (lookup_long && (s->aux[i].flags & IS_LONG)) {
666 if (len > s->aux[i].namelen)
669 if (strncmp (optname, optstart, len) == 0) {
673 /* exact match overrides all. */
674 if (len == s->aux[i].namelen) {
679 /* ambiguity is ok between aliases. */
682 s->options[i].r_val) nmatch--;
683 lastr_val = s->options[i].r_val;
686 else if (!lookup_long && !(s->aux[i].flags & IS_LONG)) {
687 if (optname[0] == optstart[0]) {
695 *err_code = SCANOPT_ERR_OPT_UNRECOGNIZED;
698 else if (nmatch > 1) {
699 *err_code = SCANOPT_ERR_OPT_AMBIGUOUS;
703 return *err_code ? 0 : 1;
707 int scanopt (svoid, arg, optindex)
712 char *optname = NULL, *optarg = NULL, *pstart;
713 int namelen = 0, arglen = 0;
714 int errcode = 0, has_next;
715 const optspec_t *optp;
716 struct _scanopt_t *s;
721 s = (struct _scanopt_t *) svoid;
723 /* Normalize return-parameters. */
724 SAFE_ASSIGN (arg, NULL);
725 SAFE_ASSIGN (optindex, s->index);
727 if (s->index >= s->argc)
730 /* pstart always points to the start of our current scan. */
731 pstart = s->argv[s->index] + s->subscript;
735 if (s->subscript == 0) {
737 /* test for exact match of "--" */
738 if (pstart[0] == '-' && pstart[1] == '-' && !pstart[2]) {
739 SAFE_ASSIGN (optindex, s->index + 1);
746 (pstart, &optname, &namelen, &optarg, &arglen)) {
748 /* it LOOKS like an opt, but is it one?! */
750 (s, 1, optname, namelen, &errcode,
752 scanopt_err (s, opt_offset, 0, errcode);
755 /* We handle this below. */
758 /* Check for short opt. */
760 else if (pstart[0] == '-' && pstart[1]) {
761 /* Pass through to below. */
768 /* It's not an option. We're done. */
773 /* We have to re-check the subscript status because it
774 * may have changed above. */
776 if (s->subscript != 0) {
778 /* we are somewhere in a run of short opts,
779 * e.g., at the 'z' in `tar -xzf` */
786 (s, 0, pstart, namelen, &errcode, &opt_offset)) {
787 return scanopt_err (s, opt_offset, 1, errcode);
796 arglen = strlen (optarg);
799 /* At this point, we have a long or short option matched at opt_offset into
800 * the s->options array (and corresponding aux array).
801 * A trailing argument is in {optarg,arglen}, if any.
804 /* Look ahead in argv[] to see if there is something
805 * that we can use as an argument (if needed). */
806 has_next = s->index + 1 < s->argc
807 && strcmp ("--", s->argv[s->index + 1]) != 0;
809 optp = s->options + opt_offset;
810 auxp = s->aux + opt_offset;
812 /* case: no args allowed */
813 if (auxp->flags & ARG_NONE) {
814 if (optarg && !is_short) {
815 scanopt_err (s, opt_offset, is_short, errcode =
816 SCANOPT_ERR_ARG_NOT_ALLOWED);
828 if (auxp->flags & ARG_REQ) {
829 if (!optarg && !has_next)
830 return scanopt_err (s, opt_offset, is_short,
831 SCANOPT_ERR_ARG_NOT_FOUND);
834 /* Let the next argv element become the argument. */
835 SAFE_ASSIGN (arg, s->argv[s->index + 1]);
839 SAFE_ASSIGN (arg, (char *) optarg);
846 if (auxp->flags & ARG_OPT) {
847 SAFE_ASSIGN (arg, optarg);
853 /* Should not reach here. */
858 int scanopt_destroy (svoid)
861 struct _scanopt_t *s;
863 s = (struct _scanopt_t *) svoid;
873 /* vim:set tabstop=8 softtabstop=4 shiftwidth=4: */