2 * Copyright (c) 1992 Diomidis Spinellis.
3 * Copyright (c) 1992, 1993
4 * The Regents of the University of California. All rights reserved.
6 * This code is derived from software contributed to Berkeley by
7 * Diomidis Spinellis of Imperial College, University of London.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. All advertising materials mentioning features or use of this software
18 * must display the following acknowledgement:
19 * This product includes software developed by the University of
20 * California, Berkeley and its contributors.
21 * 4. Neither the name of the University nor the names of its contributors
22 * may be used to endorse or promote products derived from this software
23 * without specific prior written permission.
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
42 static const char sccsid[] = "@(#)compile.c 8.1 (Berkeley) 6/6/93";
45 #include <sys/types.h>
61 #define LHMASK (LHSZ - 1)
62 static struct labhash {
63 struct labhash *lh_next;
65 struct s_command *lh_cmd;
69 static char *compile_addr(char *, struct s_addr *);
70 static char *compile_ccl(char **, char *);
71 static char *compile_delimited(char *, char *);
72 static char *compile_flags(char *, struct s_subst *);
73 static char *compile_re(char *, regex_t **);
74 static char *compile_subst(char *, struct s_subst *);
75 static char *compile_text(void);
76 static char *compile_tr(char *, char **);
77 static struct s_command
78 **compile_stream(struct s_command **);
79 static char *duptoeol(char *, const char *);
80 static void enterlabel(struct s_command *);
81 static struct s_command
83 static void fixuplabel(struct s_command *, struct s_command *);
84 static void uselabel(void);
87 * Command specification. This is used to drive the command parser.
90 char code; /* Command code */
91 int naddr; /* Number of address args */
92 enum e_args args; /* Argument type */
95 static struct s_format cmd_fmts[] = {
127 /* The compiled program. */
128 struct s_command *prog;
131 * Compile the program into prog.
132 * Initialise appends.
137 *compile_stream(&prog) = NULL;
138 fixuplabel(prog, NULL);
142 else if ((appends = malloc(sizeof(struct s_appends) * appendnum)) ==
145 if ((match = malloc((maxnsub + 1) * sizeof(regmatch_t))) == NULL)
149 #define EATSPACE() do { \
151 while (*p && isspace((unsigned char)*p)) \
155 static struct s_command **
157 struct s_command **link;
160 static char lbuf[_POSIX2_LINE_MAX + 1]; /* To save stack */
161 struct s_command *cmd, *cmd2, *stack;
163 int naddr; /* Number of addresses */
167 if ((p = cu_fgets(lbuf, sizeof(lbuf), NULL)) == NULL) {
169 errx(1, "%lu: %s: unexpected EOF (pending }'s)",
174 semicolon: EATSPACE();
175 if (p && (*p == '#' || *p == '\0'))
177 if ((*link = cmd = malloc(sizeof(struct s_command))) == NULL)
180 cmd->nonsel = cmd->inrange = 0;
181 /* First parse the addresses */
184 /* Valid characters to start an address */
185 #define addrchar(c) (strchr("0123456789/\\$", (c)))
188 if ((cmd->a1 = malloc(sizeof(struct s_addr))) == NULL)
190 p = compile_addr(p, cmd->a1);
191 EATSPACE(); /* EXTENSION */
194 EATSPACE(); /* EXTENSION */
196 if ((cmd->a2 = malloc(sizeof(struct s_addr)))
199 p = compile_addr(p, cmd->a2);
204 cmd->a1 = cmd->a2 = 0;
206 nonsel: /* Now parse the command */
208 errx(1, "%lu: %s: command expected", linenum, fname);
210 for (fp = cmd_fmts; fp->code; fp++)
214 errx(1, "%lu: %s: invalid command code %c", linenum, fname, *p);
215 if (naddr > fp->naddr)
217 "%lu: %s: command %c expects up to %d address(es), found %d",
218 linenum, fname, *p, fp->naddr, naddr);
223 cmd->nonsel = ! cmd->nonsel;
236 * Short-circuit command processing, since end of
237 * group is really just a noop.
241 errx(1, "%lu: %s: unexpected }", linenum, fname);
246 case EMPTY: /* d D g G h H l n N p P q x = \0 */
255 errx(1, "%lu: %s: extra characters at the end of %c command",
256 linenum, fname, cmd->code);
258 case TEXT: /* a c i */
263 "%lu: %s: command %c expects \\ followed by text", linenum, fname, cmd->code);
268 "%lu: %s: extra characters after \\ at the end of %c command",
269 linenum, fname, cmd->code);
270 cmd->t = compile_text();
272 case COMMENT: /* \0 # */
278 errx(1, "%lu: %s: filename expected", linenum, fname);
279 cmd->t = duptoeol(p, "w command");
282 else if ((cmd->u.fd = open(p,
283 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
291 errx(1, "%lu: %s: filename expected", linenum, fname);
293 cmd->t = duptoeol(p, "read command");
295 case BRANCH: /* b t */
301 cmd->t = duptoeol(p, "branch");
306 cmd->t = duptoeol(p, "label");
308 errx(1, "%lu: %s: empty label", linenum, fname);
313 if (*p == '\0' || *p == '\\')
315 "%lu: %s: substitute pattern can not be delimited by newline or backslash",
317 if ((cmd->u.s = malloc(sizeof(struct s_subst))) == NULL)
319 p = compile_re(p, &cmd->u.s->re);
322 "%lu: %s: unterminated substitute pattern", linenum, fname);
324 p = compile_subst(p, cmd->u.s);
325 p = compile_flags(p, cmd->u.s);
335 p = compile_tr(p, (char **)&cmd->u.y);
344 "%lu: %s: extra text at the end of a transform command", linenum, fname);
351 * Get a delimited string. P points to the delimeter of the string; d points
352 * to a buffer area. Newline and delimiter escapes are processed; other
353 * escapes are ignored.
355 * Returns a pointer to the first character after the final delimiter or NULL
356 * in the case of a non-terminated string. The character array d is filled
357 * with the processed string.
360 compile_delimited(p, d)
369 errx(1, "%lu: %s: \\ can not be used as a string delimiter",
372 errx(1, "%lu: %s: newline can not be used as a string delimiter",
376 if ((d = compile_ccl(&p, d)) == NULL)
377 errx(1, "%lu: %s: unbalanced brackets ([])", linenum, fname);
379 } else if (*p == '\\' && p[1] == '[') {
381 } else if (*p == '\\' && p[1] == c)
383 else if (*p == '\\' && p[1] == 'n') {
387 } else if (*p == '\\' && p[1] == '\\')
399 /* compile_ccl: expand a POSIX character class */
413 for (; *s && (*t = *s) != ']'; s++, t++)
414 if (*s == '[' && ((d = *(s+1)) == '.' || d == ':' || d == '=')) {
415 *++t = *++s, t++, s++;
416 for (c = *s; (*t = *s) != ']' || c != d; s++, t++)
417 if ((c = *s) == '\0')
419 } else if (*s == '\\' && s[1] == 'n')
421 return (*s == ']') ? *sp = ++s, ++t : NULL;
425 * Get a regular expression. P points to the delimiter of the regular
426 * expression; repp points to the address of a regexp pointer. Newline
427 * and delimiter escapes are processed; other escapes are ignored.
428 * Returns a pointer to the first character after the final delimiter
429 * or NULL in the case of a non terminated regular expression. The regexp
430 * pointer is set to the compiled regular expression.
431 * Cflags are passed to regcomp.
439 char re[_POSIX2_LINE_MAX + 1];
441 p = compile_delimited(p, re);
442 if (p && strlen(re) == 0) {
446 if ((*repp = malloc(sizeof(regex_t))) == NULL)
448 if (p && (eval = regcomp(*repp, re, rflags)) != 0)
449 errx(1, "%lu: %s: RE error: %s",
450 linenum, fname, strregerror(eval, *repp));
451 if (maxnsub < (*repp)->re_nsub)
452 maxnsub = (*repp)->re_nsub;
457 * Compile the substitution string of a regular expression and set res to
458 * point to a saved copy of it. Nsub is the number of parenthesized regular
466 static char lbuf[_POSIX2_LINE_MAX + 1];
469 char c, *text, *op, *sp;
470 int more = 1, sawesc = 0;
472 c = *p++; /* Terminator character */
477 s->linenum = linenum;
478 asize = 2 * _POSIX2_LINE_MAX + 1;
479 if ((text = malloc(asize)) == NULL)
483 op = sp = text + size;
485 if (*p == '\\' || sawesc) {
487 * If this is a continuation from the last
488 * buffer, we won't have a character to
498 * This escaped character is continued
499 * in the next part of the line. Note
500 * this fact, then cause the loop to
501 * exit w/ normal EOL case and reenter
502 * above with the new buffer.
507 } else if (strchr("123456789", *p) != NULL) {
511 ref > s->re->re_nsub)
512 errx(1, "%lu: %s: \\%c not defined in the RE",
514 if (s->maxbref < ref)
516 } else if (*p == '&' || *p == '\\')
518 } else if (*p == c) {
519 if (*++p == '\0' && more) {
520 if (cu_fgets(lbuf, sizeof(lbuf), &more))
525 if ((s->new = realloc(text, size)) == NULL)
528 } else if (*p == '\n') {
530 "%lu: %s: unescaped newline inside substitute pattern", linenum, fname);
536 if (asize - size < _POSIX2_LINE_MAX + 1) {
538 if ((text = realloc(text, asize)) == NULL)
541 } while (cu_fgets(p = lbuf, sizeof(lbuf), &more));
542 errx(1, "%lu: %s: unterminated substitute in regular expression",
548 * Compile the flags of the s command
555 int gn; /* True if we have seen g or n */
556 char wfile[_POSIX2_LINE_MAX + 1], *q;
558 s->n = 1; /* Default */
563 EATSPACE(); /* EXTENSION */
568 "%lu: %s: more than one number or 'g' in substitute flags", linenum, fname);
579 case '1': case '2': case '3':
580 case '4': case '5': case '6':
581 case '7': case '8': case '9':
584 "%lu: %s: more than one number or 'g' in substitute flags", linenum, fname);
586 /* XXX Check for overflow */
587 s->n = (int)strtol(p, &p, 10);
591 #ifdef HISTORIC_PRACTICE
593 warnx("%lu: %s: space missing before w wfile", linenum, fname);
606 errx(1, "%lu: %s: no wfile specified", linenum, fname);
607 s->wfile = strdup(wfile);
608 if (!aflag && (s->wfd = open(wfile,
609 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
614 errx(1, "%lu: %s: bad flag in substitute command: '%c'",
623 * Compile a translation set of strings into a lookup table.
626 compile_tr(p, transtab)
632 char old[_POSIX2_LINE_MAX + 1];
633 char new[_POSIX2_LINE_MAX + 1];
635 if (*p == '\0' || *p == '\\')
637 "%lu: %s: transform pattern can not be delimited by newline or backslash",
639 p = compile_delimited(p, old);
641 errx(1, "%lu: %s: unterminated transform source string",
643 p = compile_delimited(--p, new);
645 errx(1, "%lu: %s: unterminated transform target string",
648 if (strlen(new) != strlen(old))
649 errx(1, "%lu: %s: transform strings are not the same length",
651 /* We assume characters are 8 bits */
652 if ((lt = malloc(UCHAR_MAX)) == NULL)
654 for (i = 0; i <= UCHAR_MAX; i++)
656 for (op = old, np = new; *op; op++, np++)
657 lt[(u_char)*op] = *np;
663 * Compile the text following an a or i command.
668 int asize, esc_nl, size;
669 char *text, *p, *op, *s;
670 char lbuf[_POSIX2_LINE_MAX + 1];
672 asize = 2 * _POSIX2_LINE_MAX + 1;
673 if ((text = malloc(asize)) == NULL)
676 while (cu_fgets(lbuf, sizeof(lbuf), NULL)) {
677 op = s = text + size;
680 for (esc_nl = 0; *p != '\0'; p++) {
681 if (*p == '\\' && p[1] != '\0' && *++p == '\n')
690 if (asize - size < _POSIX2_LINE_MAX + 1) {
692 if ((text = realloc(text, asize)) == NULL)
697 if ((p = realloc(text, size + 1)) == NULL)
703 * Get an address and return a pointer to the first character after
704 * it. Fill the structure pointed to according to the address.
714 case '\\': /* Context address */
717 case '/': /* Context address */
718 p = compile_re(p, &a->u.r);
720 errx(1, "%lu: %s: unterminated regular expression", linenum, fname);
724 case '$': /* Last line */
728 case '0': case '1': case '2': case '3': case '4':
729 case '5': case '6': case '7': case '8': case '9':
731 a->u.l = strtol(p, &end, 10);
734 errx(1, "%lu: %s: expected context address", linenum, fname);
741 * Return a copy of all the characters up to \n or \0.
753 for (start = s; *s != '\0' && *s != '\n'; ++s)
754 ws = isspace((unsigned char)*s);
757 warnx("%lu: %s: whitespace after %s", linenum, fname, ctype);
759 if ((p = malloc(len)) == NULL)
761 return (memmove(p, start, len));
765 * Convert goto label names to addresses, and count a and r commands, in
766 * the given subset of the script. Free the memory used by labels in b
767 * and t commands (but not by :).
769 * TODO: Remove } nodes
773 struct s_command *cp, *end;
776 for (; cp != end; cp = cp->next)
784 /* Resolve branch target. */
789 if ((cp->u.c = findlabel(cp->t)) == NULL)
790 errx(1, "%lu: %s: undefined label '%s'", linenum, fname, cp->t);
794 /* Do interior commands. */
795 fixuplabel(cp->u.c, cp->next);
801 * Associate the given command label for later lookup.
805 struct s_command *cp;
807 struct labhash **lhp, *lh;
811 for (h = 0, p = (u_char *)cp->t; (c = *p) != 0; p++)
812 h = (h << 5) + h + c;
813 lhp = &labels[h & LHMASK];
814 for (lh = *lhp; lh != NULL; lh = lh->lh_next)
815 if (lh->lh_hash == h && strcmp(cp->t, lh->lh_cmd->t) == 0)
816 errx(1, "%lu: %s: duplicate label '%s'", linenum, fname, cp->t);
817 if ((lh = malloc(sizeof *lh)) == NULL)
827 * Find the label contained in the command l in the command linked
828 * list cp. L is excluded from the search. Return NULL if not found.
830 static struct s_command *
838 for (h = 0, p = (u_char *)name; (c = *p) != 0; p++)
839 h = (h << 5) + h + c;
840 for (lh = labels[h & LHMASK]; lh != NULL; lh = lh->lh_next) {
841 if (lh->lh_hash == h && strcmp(name, lh->lh_cmd->t) == 0) {
850 * Warn about any unused labels. As a side effect, release the label hash
856 struct labhash *lh, *next;
859 for (i = 0; i < LHSZ; i++) {
860 for (lh = labels[i]; lh != NULL; lh = next) {
863 warnx("%lu: %s: unused label '%s'",
864 linenum, fname, lh->lh_cmd->t);