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 */
46 int flags; /* The above hex flags. */
47 int namelen; /* Length of the actual option word, e.g., "--file[=foo]" is 4 */
48 int printlen; /* Length of entire string, e.g., "--file[=foo]" is 12 */
53 const optspec_t *options; /* List of options. */
54 struct _aux *aux; /* Auxiliary data about options. */
55 int optc; /* Number of options. */
56 int argc; /* Number of args. */
57 char **argv; /* Array of strings. */
58 int index; /* Used as: argv[index][subscript]. */
60 char no_err_msg; /* If true, do not print errors. */
65 /* Accessor functions. These WOULD be one-liners, but portability calls. */
66 static const char *NAME(struct _scanopt_t *, int);
67 static int PRINTLEN(struct _scanopt_t *, int);
68 static int RVAL(struct _scanopt_t *, int);
69 static int FLAGS(struct _scanopt_t *, int);
70 static const char *DESC(struct _scanopt_t *, int);
71 static int scanopt_err(struct _scanopt_t *, int, int);
72 static int matchlongopt(char *, char **, int *, char **, int *);
73 static int find_opt(struct _scanopt_t *, int, char *, int, int *, int *opt_offset);
75 static const char *NAME (struct _scanopt_t *s, int i)
77 return s->options[i].opt_fmt +
78 ((s->aux[i].flags & IS_LONG) ? 2 : 1);
81 static int PRINTLEN (struct _scanopt_t *s, int i)
83 return s->aux[i].printlen;
86 static int RVAL (struct _scanopt_t *s, int i)
88 return s->options[i].r_val;
91 static int FLAGS (struct _scanopt_t *s, int i)
93 return s->aux[i].flags;
96 static const char *DESC (struct _scanopt_t *s, int i)
98 return s->options[i].desc ? s->options[i].desc : "";
101 #ifndef NO_SCANOPT_USAGE
102 static int get_cols (void);
104 static int get_cols (void)
107 int cols = 80; /* default */
109 #ifdef HAVE_NCURSES_H
116 if ((env = getenv ("COLUMNS")) != NULL)
123 /* Macro to check for NULL before assigning a value. */
124 #define SAFE_ASSIGN(ptr,val) \
130 /* Macro to assure we reset subscript whenever we adjust s->index.*/
131 #define INC_INDEX(s,n) \
137 scanopt_t *scanopt_init (const optspec_t *options, int argc, char **argv, int flags)
140 struct _scanopt_t *s;
141 s = malloc(sizeof (struct _scanopt_t));
143 s->options = options;
146 s->argv = (char **) argv;
149 s->no_err_msg = (flags & SCANOPT_NO_ERR_MSG);
153 /* Determine option count. (Find entry with all zeros). */
155 while (options[s->optc].opt_fmt
156 || options[s->optc].r_val || options[s->optc].desc)
159 /* Build auxiliary data */
160 s->aux = malloc((size_t) s->optc * sizeof (struct _aux));
162 for (i = 0; i < s->optc; i++) {
163 const unsigned char *p, *pname;
164 const struct optspec_t *opt;
167 opt = s->options + i;
170 aux->flags = ARG_NONE;
172 if (opt->opt_fmt[0] == '-' && opt->opt_fmt[1] == '-') {
173 aux->flags |= IS_LONG;
174 pname = (const unsigned char *)(opt->opt_fmt + 2);
178 pname = (const unsigned char *)(opt->opt_fmt + 1);
181 aux->printlen = (int) strlen (opt->opt_fmt);
184 for (p = pname + 1; *p; p++) {
185 /* detect required arg */
186 if (*p == '=' || isspace ((unsigned char)*p)
187 || !(aux->flags & IS_LONG)) {
188 if (aux->namelen == 0)
189 aux->namelen = (int) (p - pname);
190 aux->flags |= ARG_REQ;
191 aux->flags &= ~ARG_NONE;
193 /* detect optional arg. This overrides required arg. */
195 if (aux->namelen == 0)
196 aux->namelen = (int) (p - pname);
197 aux->flags &= ~(ARG_REQ | ARG_NONE);
198 aux->flags |= ARG_OPT;
202 if (aux->namelen == 0)
203 aux->namelen = (int) (p - pname);
205 return (scanopt_t *) s;
208 #ifndef NO_SCANOPT_USAGE
209 /* these structs are for scanopt_usage(). */
212 struct usg_elem *next;
213 struct usg_elem *alias;
215 typedef struct usg_elem usg_elem;
218 /* Prints a usage message based on contents of optlist.
220 * scanner - The scanner, already initialized with scanopt_init().
221 * fp - The file stream to write to.
222 * usage - Text to be prepended to option list.
223 * Return: Always returns 0 (zero).
224 * The output looks something like this:
226 [indent][option, alias1, alias2...][indent][description line1
227 description line2...]
229 int scanopt_usage (scanopt_t *scanner, FILE *fp, const char *usage)
231 struct _scanopt_t *s;
232 int i, columns, indent = 2;
233 usg_elem *byr_val = NULL; /* option indices sorted by r_val */
234 usg_elem *store; /* array of preallocated elements. */
244 s = (struct _scanopt_t *) scanner;
247 fprintf (fp, "%s\n", usage);
250 /* Find the basename of argv[0] */
253 p = s->argv[0] + strlen (s->argv[0]);
254 while (p != s->argv[0] && *p != '/')
259 fprintf (fp, _("Usage: %s [OPTIONS]...\n"), p);
263 /* Sort by r_val and string. Yes, this is O(n*n), but n is small. */
264 store = malloc((size_t) s->optc * sizeof (usg_elem));
265 for (i = 0; i < s->optc; i++) {
267 /* grab the next preallocate node. */
268 ue = store + store_idx++;
270 ue->next = ue->alias = NULL;
272 /* insert into list. */
277 usg_elem **ue_curr, **ptr_if_no_alias = NULL;
281 if (RVAL (s, (*ue_curr)->idx) ==
283 /* push onto the alias list. */
284 ue_curr = &((*ue_curr)->alias);
290 strcasecmp (NAME (s, (*ue_curr)->idx),
291 NAME (s, ue->idx)) > 0) {
292 ptr_if_no_alias = ue_curr;
294 ue_curr = &((*ue_curr)->next);
296 if (!found_alias && ptr_if_no_alias)
297 ue_curr = ptr_if_no_alias;
305 printf ("ORIGINAL:\n");
306 for (i = 0; i < s->optc; i++)
307 printf ("%2d: %s\n", i, NAME (s, i));
308 printf ("SORTED:\n");
313 printf ("%2d: %s\n", ue->idx, NAME (s, ue->idx));
314 for (ue2 = ue->alias; ue2; ue2 = ue2->next)
315 printf (" +---> %2d: %s\n", ue2->idx,
322 /* Now build each row of output. */
324 /* first pass calculate how much room we need. */
325 for (ue = byr_val; ue; ue = ue->next) {
328 int nshort = 0, nlong = 0;
331 #define CALC_LEN(i) do {\
332 if(FLAGS(s,i) & IS_LONG) \
333 len += (nlong++||nshort) ? 2+PRINTLEN(s,i) : PRINTLEN(s,i);\
335 len += (nshort++||nlong)? 2+PRINTLEN(s,i) : PRINTLEN(s,i);\
338 if (!(FLAGS (s, ue->idx) & IS_LONG))
341 /* do short aliases first. */
342 for (ap = ue->alias; ap; ap = ap->next) {
343 if (FLAGS (s, ap->idx) & IS_LONG)
348 if (FLAGS (s, ue->idx) & IS_LONG)
351 /* repeat the above loop, this time for long aliases. */
352 for (ap = ue->alias; ap; ap = ap->next) {
353 if (!(FLAGS (s, ap->idx) & IS_LONG))
361 /* It's much easier to calculate length for description column! */
362 len = (int) strlen (DESC (s, ue->idx));
367 /* Determine how much room we have, and how much we will allocate to each col.
368 * Do not address pathological cases. Output will just be ugly. */
369 columns = get_cols () - 1;
370 if (maxlen[0] + maxlen[1] + indent * 2 > columns) {
371 /* col 0 gets whatever it wants. we'll wrap the desc col. */
372 maxlen[1] = columns - (maxlen[0] + indent * 2);
373 if (maxlen[1] < 14) /* 14 is arbitrary lower limit on desc width. */
376 desccol = maxlen[0] + indent * 2;
378 #define PRINT_SPACES(fp,n)\
387 /* Second pass (same as above loop), this time we print. */
388 /* Sloppy hack: We iterate twice. The first time we print short and long options.
389 The second time we print those lines that have ONLY long options. */
390 while (print_run++ < 2) {
391 for (ue = byr_val; ue; ue = ue->next) {
393 int nwords = 0, nchars = 0, has_short = 0;
395 /* TODO: get has_short schtick to work */
396 has_short = !(FLAGS (s, ue->idx) & IS_LONG);
397 for (ap = ue->alias; ap; ap = ap->next) {
398 if (!(FLAGS (s, ap->idx) & IS_LONG)) {
403 if ((print_run == 1 && !has_short) ||
404 (print_run == 2 && has_short))
407 PRINT_SPACES (fp, indent);
410 /* Print, adding a ", " between aliases. */
411 #define PRINT_IT(i) do{\
413 nchars+=fprintf(fp,", ");\
414 nchars+=fprintf(fp,"%s",s->options[i].opt_fmt);\
417 if (!(FLAGS (s, ue->idx) & IS_LONG))
420 /* print short aliases first. */
421 for (ap = ue->alias; ap; ap = ap->next) {
422 if (!(FLAGS (s, ap->idx) & IS_LONG))
427 if (FLAGS (s, ue->idx) & IS_LONG)
430 /* repeat the above loop, this time for long aliases. */
431 for (ap = ue->alias; ap; ap = ap->next) {
432 if (FLAGS (s, ap->idx) & IS_LONG)
437 PRINT_SPACES (fp, desccol - nchars);
439 /* Print description, wrapped to maxlen[1] columns. */
443 pstart = DESC (s, ue->idx);
446 const char *lastws = NULL, *p;
450 while (*p && n < maxlen[1]
452 if (isspace ((unsigned char)(*p))
453 || *p == '-') lastws =
459 if (!*p) { /* hit end of desc. done. */
464 else if (*p == '\n') { /* print everything up to here then wrap. */
465 fprintf (fp, "%.*s\n", n,
467 PRINT_SPACES (fp, desccol);
471 else { /* we hit the edge of the screen. wrap at space if possible. */
475 (int)(lastws - pstart),
487 PRINT_SPACES (fp, desccol);
497 #endif /* no scanopt_usage */
500 static int scanopt_err (struct _scanopt_t *s, int is_short, int err)
502 const char *optname = "";
505 if (!s->no_err_msg) {
507 if (s->index > 0 && s->index < s->argc) {
510 s->argv[s->index][s->subscript];
515 optname = s->argv[s->index];
519 fprintf (stderr, "%s: ", s->argv[0]);
521 case SCANOPT_ERR_ARG_NOT_ALLOWED:
524 ("option `%s' doesn't allow an argument\n"),
527 case SCANOPT_ERR_ARG_NOT_FOUND:
529 _("option `%s' requires an argument\n"),
532 case SCANOPT_ERR_OPT_AMBIGUOUS:
533 fprintf (stderr, _("option `%s' is ambiguous\n"),
536 case SCANOPT_ERR_OPT_UNRECOGNIZED:
537 fprintf (stderr, _("Unrecognized option `%s'\n"),
541 fprintf (stderr, _("Unknown error=(%d)\n"), err);
549 /* Internal. Match str against the regex ^--([^=]+)(=(.*))?
550 * return 1 if *looks* like a long option.
551 * 'str' is the only input argument, the rest of the arguments are output only.
552 * optname will point to str + 2
555 static int matchlongopt (char *str, char **optname, int *optlen, char **arg, int *arglen)
559 *optname = *arg = NULL;
560 *optlen = *arglen = 0;
562 /* Match regex /--./ */
564 if (p[0] != '-' || p[1] != '-' || !p[2])
570 /* find the end of optname */
571 while (*p && *p != '=')
574 *optlen = (int) (p - *optname);
577 /* an option with no '=...' part. */
581 /* We saw an '=' char. The rest of p is the arg. */
586 *arglen = (int) (p - *arg);
592 /* Internal. Look up long or short option by name.
593 * Long options must match a non-ambiguous prefix, or exact match.
594 * Short options must be exact.
595 * Return boolean true if found and no error.
596 * Error stored in err_code or zero if no error. */
597 static int find_opt (struct _scanopt_t *s, int lookup_long, char *optstart, int
598 len, int *err_code, int *opt_offset)
600 int nmatch = 0, lastr_val = 0, i;
608 for (i = 0; i < s->optc; i++) {
611 optname = s->options[i].opt_fmt + (lookup_long ? 2 : 1);
613 if (lookup_long && (s->aux[i].flags & IS_LONG)) {
614 if (len > s->aux[i].namelen)
617 if (strncmp (optname, optstart, (size_t) len) == 0) {
621 /* exact match overrides all. */
622 if (len == s->aux[i].namelen) {
627 /* ambiguity is ok between aliases. */
630 s->options[i].r_val) nmatch--;
631 lastr_val = s->options[i].r_val;
634 else if (!lookup_long && !(s->aux[i].flags & IS_LONG)) {
635 if (optname[0] == optstart[0]) {
643 *err_code = SCANOPT_ERR_OPT_UNRECOGNIZED;
646 else if (nmatch > 1) {
647 *err_code = SCANOPT_ERR_OPT_AMBIGUOUS;
651 return *err_code ? 0 : 1;
655 int scanopt (scanopt_t *svoid, char **arg, int *optindex)
657 char *optname = NULL, *optarg = NULL, *pstart;
658 int namelen = 0, arglen = 0;
659 int errcode = 0, has_next;
660 const optspec_t *optp;
661 struct _scanopt_t *s;
666 s = (struct _scanopt_t *) svoid;
668 /* Normalize return-parameters. */
669 SAFE_ASSIGN (arg, NULL);
670 SAFE_ASSIGN (optindex, s->index);
672 if (s->index >= s->argc)
675 /* pstart always points to the start of our current scan. */
676 pstart = s->argv[s->index] + s->subscript;
680 if (s->subscript == 0) {
682 /* test for exact match of "--" */
683 if (pstart[0] == '-' && pstart[1] == '-' && !pstart[2]) {
684 SAFE_ASSIGN (optindex, s->index + 1);
691 (pstart, &optname, &namelen, &optarg, &arglen)) {
693 /* it LOOKS like an opt, but is it one?! */
695 (s, 1, optname, namelen, &errcode,
697 scanopt_err (s, 0, errcode);
700 /* We handle this below. */
703 /* Check for short opt. */
705 else if (pstart[0] == '-' && pstart[1]) {
706 /* Pass through to below. */
713 /* It's not an option. We're done. */
718 /* We have to re-check the subscript status because it
719 * may have changed above. */
721 if (s->subscript != 0) {
723 /* we are somewhere in a run of short opts,
724 * e.g., at the 'z' in `tar -xzf` */
731 (s, 0, pstart, namelen, &errcode, &opt_offset)) {
732 return scanopt_err (s, 1, errcode);
741 arglen = (int) strlen (optarg);
744 /* At this point, we have a long or short option matched at opt_offset into
745 * the s->options array (and corresponding aux array).
746 * A trailing argument is in {optarg,arglen}, if any.
749 /* Look ahead in argv[] to see if there is something
750 * that we can use as an argument (if needed). */
751 has_next = s->index + 1 < s->argc
752 && strcmp ("--", s->argv[s->index + 1]) != 0;
754 optp = s->options + opt_offset;
755 auxp = s->aux + opt_offset;
757 /* case: no args allowed */
758 if (auxp->flags & ARG_NONE) {
759 if (optarg && !is_short) {
760 scanopt_err (s, is_short, errcode = SCANOPT_ERR_ARG_NOT_ALLOWED);
772 if (auxp->flags & ARG_REQ) {
773 if (!optarg && !has_next)
774 return scanopt_err (s, is_short, SCANOPT_ERR_ARG_NOT_FOUND);
777 /* Let the next argv element become the argument. */
778 SAFE_ASSIGN (arg, s->argv[s->index + 1]);
782 SAFE_ASSIGN (arg, (char *) optarg);
789 if (auxp->flags & ARG_OPT) {
790 SAFE_ASSIGN (arg, optarg);
796 /* Should not reach here. */
801 int scanopt_destroy (scanopt_t *svoid)
803 struct _scanopt_t *s;
805 s = (struct _scanopt_t *) svoid;
814 /* vim:set tabstop=8 softtabstop=4 shiftwidth=4: */