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 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
38 static const char sccsid[] = "@(#)compile.c 8.1 (Berkeley) 6/6/93";
41 #include <sys/types.h>
59 #define LHMASK (LHSZ - 1)
60 static struct labhash {
61 struct labhash *lh_next;
63 struct s_command *lh_cmd;
67 static char *compile_addr(char *, struct s_addr *);
68 static char *compile_ccl(char **, char *);
69 static char *compile_delimited(char *, char *);
70 static char *compile_flags(char *, struct s_subst *);
71 static char *compile_re(char *, regex_t **);
72 static char *compile_subst(char *, struct s_subst *);
73 static char *compile_text(void);
74 static char *compile_tr(char *, struct s_tr **);
75 static struct s_command
76 **compile_stream(struct s_command **);
77 static char *duptoeol(char *, const char *);
78 static void enterlabel(struct s_command *);
79 static struct s_command
81 static void fixuplabel(struct s_command *, struct s_command *);
82 static void uselabel(void);
85 * Command specification. This is used to drive the command parser.
88 char code; /* Command code */
89 int naddr; /* Number of address args */
90 enum e_args args; /* Argument type */
93 static struct s_format cmd_fmts[] = {
125 /* The compiled program. */
126 struct s_command *prog;
129 * Compile the program into prog.
130 * Initialise appends.
135 *compile_stream(&prog) = NULL;
136 fixuplabel(prog, NULL);
140 else if ((appends = malloc(sizeof(struct s_appends) * appendnum)) ==
143 if ((match = malloc((maxnsub + 1) * sizeof(regmatch_t))) == NULL)
147 #define EATSPACE() do { \
149 while (*p && isspace((unsigned char)*p)) \
153 static struct s_command **
154 compile_stream(struct s_command **link)
157 static char lbuf[_POSIX2_LINE_MAX + 1]; /* To save stack */
158 struct s_command *cmd, *cmd2, *stack;
160 int naddr; /* Number of addresses */
164 if ((p = cu_fgets(lbuf, sizeof(lbuf), NULL)) == NULL) {
166 errx(1, "%lu: %s: unexpected EOF (pending }'s)",
171 semicolon: EATSPACE();
173 if (*p == '#' || *p == '\0')
175 else if (*p == ';') {
180 if ((*link = cmd = malloc(sizeof(struct s_command))) == NULL)
183 cmd->nonsel = cmd->inrange = 0;
184 /* First parse the addresses */
187 /* Valid characters to start an address */
188 #define addrchar(c) (strchr("0123456789/\\$", (c)))
191 if ((cmd->a1 = malloc(sizeof(struct s_addr))) == NULL)
193 p = compile_addr(p, cmd->a1);
194 EATSPACE(); /* EXTENSION */
197 EATSPACE(); /* EXTENSION */
199 if ((cmd->a2 = malloc(sizeof(struct s_addr)))
202 p = compile_addr(p, cmd->a2);
207 cmd->a1 = cmd->a2 = 0;
209 nonsel: /* Now parse the command */
211 errx(1, "%lu: %s: command expected", linenum, fname);
213 for (fp = cmd_fmts; fp->code; fp++)
217 errx(1, "%lu: %s: invalid command code %c", linenum, fname, *p);
218 if (naddr > fp->naddr)
220 "%lu: %s: command %c expects up to %d address(es), found %d",
221 linenum, fname, *p, fp->naddr, naddr);
226 cmd->nonsel = ! cmd->nonsel;
239 * Short-circuit command processing, since end of
240 * group is really just a noop.
244 errx(1, "%lu: %s: unexpected }", linenum, fname);
249 case EMPTY: /* d D g G h H l n N p P q x = \0 */
258 errx(1, "%lu: %s: extra characters at the end of %c command",
259 linenum, fname, cmd->code);
261 case TEXT: /* a c i */
266 "%lu: %s: command %c expects \\ followed by text", linenum, fname, cmd->code);
271 "%lu: %s: extra characters after \\ at the end of %c command",
272 linenum, fname, cmd->code);
273 cmd->t = compile_text();
275 case COMMENT: /* \0 # */
281 errx(1, "%lu: %s: filename expected", linenum, fname);
282 cmd->t = duptoeol(p, "w command");
285 else if ((cmd->u.fd = open(p,
286 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
294 errx(1, "%lu: %s: filename expected", linenum, fname);
296 cmd->t = duptoeol(p, "read command");
298 case BRANCH: /* b t */
304 cmd->t = duptoeol(p, "branch");
309 cmd->t = duptoeol(p, "label");
311 errx(1, "%lu: %s: empty label", linenum, fname);
316 if (*p == '\0' || *p == '\\')
318 "%lu: %s: substitute pattern can not be delimited by newline or backslash",
320 if ((cmd->u.s = malloc(sizeof(struct s_subst))) == NULL)
322 p = compile_re(p, &cmd->u.s->re);
325 "%lu: %s: unterminated substitute pattern", linenum, fname);
327 p = compile_subst(p, cmd->u.s);
328 p = compile_flags(p, cmd->u.s);
338 p = compile_tr(p, &cmd->u.y);
347 "%lu: %s: extra text at the end of a transform command", linenum, fname);
354 * Get a delimited string. P points to the delimeter of the string; d points
355 * to a buffer area. Newline and delimiter escapes are processed; other
356 * escapes are ignored.
358 * Returns a pointer to the first character after the final delimiter or NULL
359 * in the case of a non-terminated string. The character array d is filled
360 * with the processed string.
363 compile_delimited(char *p, char *d)
371 errx(1, "%lu: %s: \\ can not be used as a string delimiter",
374 errx(1, "%lu: %s: newline can not be used as a string delimiter",
378 if ((d = compile_ccl(&p, d)) == NULL)
379 errx(1, "%lu: %s: unbalanced brackets ([])", linenum, fname);
381 } else if (*p == '\\' && p[1] == '[') {
383 } else if (*p == '\\' && p[1] == c)
385 else if (*p == '\\' && p[1] == 'n') {
389 } else if (*p == '\\' && p[1] == '\\')
401 /* compile_ccl: expand a POSIX character class */
403 compile_ccl(char **sp, char *t)
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.
434 compile_re(char *p, regex_t **repp)
437 char re[_POSIX2_LINE_MAX + 1];
439 p = compile_delimited(p, re);
440 if (p && strlen(re) == 0) {
444 if ((*repp = malloc(sizeof(regex_t))) == NULL)
446 if (p && (eval = regcomp(*repp, re, rflags)) != 0)
447 errx(1, "%lu: %s: RE error: %s",
448 linenum, fname, strregerror(eval, *repp));
449 if (maxnsub < (*repp)->re_nsub)
450 maxnsub = (*repp)->re_nsub;
455 * Compile the substitution string of a regular expression and set res to
456 * point to a saved copy of it. Nsub is the number of parenthesized regular
460 compile_subst(char *p, struct s_subst *s)
462 static char lbuf[_POSIX2_LINE_MAX + 1];
465 char c, *text, *op, *sp;
466 int more = 1, sawesc = 0;
468 c = *p++; /* Terminator character */
473 s->linenum = linenum;
474 asize = 2 * _POSIX2_LINE_MAX + 1;
475 if ((text = malloc(asize)) == NULL)
479 op = sp = text + size;
481 if (*p == '\\' || sawesc) {
483 * If this is a continuation from the last
484 * buffer, we won't have a character to
494 * This escaped character is continued
495 * in the next part of the line. Note
496 * this fact, then cause the loop to
497 * exit w/ normal EOL case and reenter
498 * above with the new buffer.
503 } else if (strchr("123456789", *p) != NULL) {
507 ref > s->re->re_nsub)
508 errx(1, "%lu: %s: \\%c not defined in the RE",
510 if (s->maxbref < ref)
512 } else if (*p == '&' || *p == '\\')
514 } else if (*p == c) {
515 if (*++p == '\0' && more) {
516 if (cu_fgets(lbuf, sizeof(lbuf), &more))
521 if ((s->new = realloc(text, size)) == NULL)
524 } else if (*p == '\n') {
526 "%lu: %s: unescaped newline inside substitute pattern", linenum, fname);
532 if (asize - size < _POSIX2_LINE_MAX + 1) {
534 if ((text = realloc(text, asize)) == NULL)
537 } while (cu_fgets(p = lbuf, sizeof(lbuf), &more));
538 errx(1, "%lu: %s: unterminated substitute in regular expression",
544 * Compile the flags of the s command
547 compile_flags(char *p, struct s_subst *s)
549 int gn; /* True if we have seen g or n */
550 char wfile[_POSIX2_LINE_MAX + 1], *q;
552 s->n = 1; /* Default */
557 EATSPACE(); /* EXTENSION */
562 "%lu: %s: more than one number or 'g' in substitute flags", linenum, fname);
573 case '1': case '2': case '3':
574 case '4': case '5': case '6':
575 case '7': case '8': case '9':
578 "%lu: %s: more than one number or 'g' in substitute flags", linenum, fname);
580 /* XXX Check for overflow */
581 s->n = (int)strtol(p, &p, 10);
585 #ifdef HISTORIC_PRACTICE
587 warnx("%lu: %s: space missing before w wfile", linenum, fname);
600 errx(1, "%lu: %s: no wfile specified", linenum, fname);
601 s->wfile = strdup(wfile);
602 if (!aflag && (s->wfd = open(wfile,
603 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
608 errx(1, "%lu: %s: bad flag in substitute command: '%c'",
617 * Compile a translation set of strings into a lookup table.
620 compile_tr(char *p, struct s_tr **py)
625 char old[_POSIX2_LINE_MAX + 1];
626 char new[_POSIX2_LINE_MAX + 1];
627 size_t oclen, oldlen, nclen, newlen;
628 mbstate_t mbs1, mbs2;
630 if ((*py = y = malloc(sizeof(*y))) == NULL)
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 - 1, new);
645 errx(1, "%lu: %s: unterminated transform target string",
649 oldlen = mbsrtowcs(NULL, &op, 0, NULL);
650 if (oldlen == (size_t)-1)
653 newlen = mbsrtowcs(NULL, &np, 0, NULL);
654 if (newlen == (size_t)-1)
656 if (newlen != oldlen)
657 errx(1, "%lu: %s: transform strings are not the same length",
659 if (MB_CUR_MAX == 1) {
661 * The single-byte encoding case is easy: generate a
664 for (i = 0; i <= UCHAR_MAX; i++)
665 y->bytetab[i] = (char)i;
666 for (; *op; op++, np++)
667 y->bytetab[(u_char)*op] = *np;
670 * Multi-byte encoding case: generate a lookup table as
671 * above, but only for single-byte characters. The first
672 * bytes of multi-byte characters have their lookup table
673 * entries set to 0, which causes do_tr() to search through
674 * an auxiliary vector of multi-byte mappings.
676 memset(&mbs1, 0, sizeof(mbs1));
677 memset(&mbs2, 0, sizeof(mbs2));
678 for (i = 0; i <= UCHAR_MAX; i++)
679 y->bytetab[i] = (btowc(i) != WEOF) ? i : 0;
680 while (*op != '\0') {
681 oclen = mbrlen(op, MB_LEN_MAX, &mbs1);
682 if (oclen == (size_t)-1 || oclen == (size_t)-2)
683 errc(1, EILSEQ, NULL);
684 nclen = mbrlen(np, MB_LEN_MAX, &mbs2);
685 if (nclen == (size_t)-1 || nclen == (size_t)-2)
686 errc(1, EILSEQ, NULL);
687 if (oclen == 1 && nclen == 1)
688 y->bytetab[(u_char)*op] = *np;
690 y->bytetab[(u_char)*op] = 0;
691 y->multis = realloc(y->multis,
692 (y->nmultis + 1) * sizeof(*y->multis));
693 if (y->multis == NULL)
696 y->multis[i].fromlen = oclen;
697 memcpy(y->multis[i].from, op, oclen);
698 y->multis[i].tolen = nclen;
699 memcpy(y->multis[i].to, np, nclen);
709 * Compile the text following an a or i command.
714 int asize, esc_nl, size;
715 char *text, *p, *op, *s;
716 char lbuf[_POSIX2_LINE_MAX + 1];
718 asize = 2 * _POSIX2_LINE_MAX + 1;
719 if ((text = malloc(asize)) == NULL)
722 while (cu_fgets(lbuf, sizeof(lbuf), NULL)) {
723 op = s = text + size;
726 for (esc_nl = 0; *p != '\0'; p++) {
727 if (*p == '\\' && p[1] != '\0' && *++p == '\n')
736 if (asize - size < _POSIX2_LINE_MAX + 1) {
738 if ((text = realloc(text, asize)) == NULL)
743 if ((p = realloc(text, size + 1)) == NULL)
749 * Get an address and return a pointer to the first character after
750 * it. Fill the structure pointed to according to the address.
753 compile_addr(char *p, struct s_addr *a)
758 case '\\': /* Context address */
761 case '/': /* Context address */
762 p = compile_re(p, &a->u.r);
764 errx(1, "%lu: %s: unterminated regular expression", linenum, fname);
768 case '$': /* Last line */
772 case '0': case '1': case '2': case '3': case '4':
773 case '5': case '6': case '7': case '8': case '9':
775 a->u.l = strtol(p, &end, 10);
778 errx(1, "%lu: %s: expected context address", linenum, fname);
785 * Return a copy of all the characters up to \n or \0.
788 duptoeol(char *s, const char *ctype)
795 for (start = s; *s != '\0' && *s != '\n'; ++s)
796 ws = isspace((unsigned char)*s);
799 warnx("%lu: %s: whitespace after %s", linenum, fname, ctype);
801 if ((p = malloc(len)) == NULL)
803 return (memmove(p, start, len));
807 * Convert goto label names to addresses, and count a and r commands, in
808 * the given subset of the script. Free the memory used by labels in b
809 * and t commands (but not by :).
811 * TODO: Remove } nodes
814 fixuplabel(struct s_command *cp, struct s_command *end)
817 for (; cp != end; cp = cp->next)
825 /* Resolve branch target. */
830 if ((cp->u.c = findlabel(cp->t)) == NULL)
831 errx(1, "%lu: %s: undefined label '%s'", linenum, fname, cp->t);
835 /* Do interior commands. */
836 fixuplabel(cp->u.c, cp->next);
842 * Associate the given command label for later lookup.
845 enterlabel(struct s_command *cp)
847 struct labhash **lhp, *lh;
851 for (h = 0, p = (u_char *)cp->t; (c = *p) != 0; p++)
852 h = (h << 5) + h + c;
853 lhp = &labels[h & LHMASK];
854 for (lh = *lhp; lh != NULL; lh = lh->lh_next)
855 if (lh->lh_hash == h && strcmp(cp->t, lh->lh_cmd->t) == 0)
856 errx(1, "%lu: %s: duplicate label '%s'", linenum, fname, cp->t);
857 if ((lh = malloc(sizeof *lh)) == NULL)
867 * Find the label contained in the command l in the command linked
868 * list cp. L is excluded from the search. Return NULL if not found.
870 static struct s_command *
871 findlabel(char *name)
877 for (h = 0, p = (u_char *)name; (c = *p) != 0; p++)
878 h = (h << 5) + h + c;
879 for (lh = labels[h & LHMASK]; lh != NULL; lh = lh->lh_next) {
880 if (lh->lh_hash == h && strcmp(name, lh->lh_cmd->t) == 0) {
889 * Warn about any unused labels. As a side effect, release the label hash
895 struct labhash *lh, *next;
898 for (i = 0; i < LHSZ; i++) {
899 for (lh = labels[i]; lh != NULL; lh = next) {
902 warnx("%lu: %s: unused label '%s'",
903 linenum, fname, lh->lh_cmd->t);