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
37 * @(#)compile.c 8.1 (Berkeley) 6/6/93
38 * $FreeBSD: src/usr.bin/sed/compile.c,v 1.13.2.8 2002/08/17 05:47:06 tjr Exp $
39 * $DragonFly: src/usr.bin/sed/compile.c,v 1.2 2003/06/17 04:29:31 dillon Exp $
42 #include <sys/types.h>
58 #define LHMASK (LHSZ - 1)
59 static struct labhash {
60 struct labhash *lh_next;
62 struct s_command *lh_cmd;
66 static char *compile_addr(char *, struct s_addr *);
67 static char *compile_ccl(char **, char *);
68 static char *compile_delimited(char *, char *);
69 static char *compile_flags(char *, struct s_subst *);
70 static char *compile_re(char *, regex_t **);
71 static char *compile_subst(char *, struct s_subst *);
72 static char *compile_text(void);
73 static char *compile_tr(char *, char **);
74 static struct s_command
75 **compile_stream(struct s_command **);
76 static char *duptoeol(char *, const char *);
77 static void enterlabel(struct s_command *);
78 static struct s_command
80 static void fixuplabel(struct s_command *, struct s_command *);
81 static void uselabel(void);
84 * Command specification. This is used to drive the command parser.
87 char code; /* Command code */
88 int naddr; /* Number of address args */
89 enum e_args args; /* Argument type */
92 static struct s_format cmd_fmts[] = {
124 /* The compiled program. */
125 struct s_command *prog;
128 * Compile the program into prog.
129 * Initialise appends.
134 *compile_stream(&prog) = NULL;
135 fixuplabel(prog, NULL);
139 else if ((appends = malloc(sizeof(struct s_appends) * appendnum)) ==
142 if ((match = malloc((maxnsub + 1) * sizeof(regmatch_t))) == NULL)
146 #define EATSPACE() do { \
148 while (*p && isspace((unsigned char)*p)) \
152 static struct s_command **
154 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, (char **)&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(p, d)
372 errx(1, "%lu: %s: \\ can not be used as a string delimiter",
375 errx(1, "%lu: %s: newline can not be used as a string delimiter",
379 if ((d = compile_ccl(&p, d)) == NULL)
380 errx(1, "%lu: %s: unbalanced brackets ([])", linenum, fname);
382 } else if (*p == '\\' && p[1] == '[') {
384 } else if (*p == '\\' && p[1] == c)
386 else if (*p == '\\' && p[1] == 'n') {
390 } else if (*p == '\\' && p[1] == '\\')
402 /* compile_ccl: expand a POSIX character class */
416 for (; *s && (*t = *s) != ']'; s++, t++)
417 if (*s == '[' && ((d = *(s+1)) == '.' || d == ':' || d == '=')) {
418 *++t = *++s, t++, s++;
419 for (c = *s; (*t = *s) != ']' || c != d; s++, t++)
420 if ((c = *s) == '\0')
422 } else if (*s == '\\' && s[1] == 'n')
424 return (*s == ']') ? *sp = ++s, ++t : NULL;
428 * Get a regular expression. P points to the delimiter of the regular
429 * expression; repp points to the address of a regexp pointer. Newline
430 * and delimiter escapes are processed; other escapes are ignored.
431 * Returns a pointer to the first character after the final delimiter
432 * or NULL in the case of a non terminated regular expression. The regexp
433 * pointer is set to the compiled regular expression.
434 * Cflags are passed to regcomp.
442 char re[_POSIX2_LINE_MAX + 1];
444 p = compile_delimited(p, re);
445 if (p && strlen(re) == 0) {
449 if ((*repp = malloc(sizeof(regex_t))) == NULL)
451 if (p && (eval = regcomp(*repp, re, rflags)) != 0)
452 errx(1, "%lu: %s: RE error: %s",
453 linenum, fname, strregerror(eval, *repp));
454 if (maxnsub < (*repp)->re_nsub)
455 maxnsub = (*repp)->re_nsub;
460 * Compile the substitution string of a regular expression and set res to
461 * point to a saved copy of it. Nsub is the number of parenthesized regular
469 static char lbuf[_POSIX2_LINE_MAX + 1];
472 char c, *text, *op, *sp;
473 int more = 1, sawesc = 0;
475 c = *p++; /* Terminator character */
480 s->linenum = linenum;
481 asize = 2 * _POSIX2_LINE_MAX + 1;
482 if ((text = malloc(asize)) == NULL)
486 op = sp = text + size;
488 if (*p == '\\' || sawesc) {
490 * If this is a continuation from the last
491 * buffer, we won't have a character to
501 * This escaped character is continued
502 * in the next part of the line. Note
503 * this fact, then cause the loop to
504 * exit w/ normal EOL case and reenter
505 * above with the new buffer.
510 } else if (strchr("123456789", *p) != NULL) {
514 ref > s->re->re_nsub)
515 errx(1, "%lu: %s: \\%c not defined in the RE",
517 if (s->maxbref < ref)
519 } else if (*p == '&' || *p == '\\')
521 } else if (*p == c) {
522 if (*++p == '\0' && more) {
523 if (cu_fgets(lbuf, sizeof(lbuf), &more))
528 if ((s->new = realloc(text, size)) == NULL)
531 } else if (*p == '\n') {
533 "%lu: %s: unescaped newline inside substitute pattern", linenum, fname);
539 if (asize - size < _POSIX2_LINE_MAX + 1) {
541 if ((text = realloc(text, asize)) == NULL)
544 } while (cu_fgets(p = lbuf, sizeof(lbuf), &more));
545 errx(1, "%lu: %s: unterminated substitute in regular expression",
551 * Compile the flags of the s command
558 int gn; /* True if we have seen g or n */
559 char wfile[_POSIX2_LINE_MAX + 1], *q;
561 s->n = 1; /* Default */
566 EATSPACE(); /* EXTENSION */
571 "%lu: %s: more than one number or 'g' in substitute flags", linenum, fname);
582 case '1': case '2': case '3':
583 case '4': case '5': case '6':
584 case '7': case '8': case '9':
587 "%lu: %s: more than one number or 'g' in substitute flags", linenum, fname);
589 /* XXX Check for overflow */
590 s->n = (int)strtol(p, &p, 10);
594 #ifdef HISTORIC_PRACTICE
596 warnx("%lu: %s: space missing before w wfile", linenum, fname);
609 errx(1, "%lu: %s: no wfile specified", linenum, fname);
610 s->wfile = strdup(wfile);
611 if (!aflag && (s->wfd = open(wfile,
612 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
617 errx(1, "%lu: %s: bad flag in substitute command: '%c'",
626 * Compile a translation set of strings into a lookup table.
629 compile_tr(p, transtab)
635 char old[_POSIX2_LINE_MAX + 1];
636 char new[_POSIX2_LINE_MAX + 1];
638 if (*p == '\0' || *p == '\\')
640 "%lu: %s: transform pattern can not be delimited by newline or backslash",
642 p = compile_delimited(p, old);
644 errx(1, "%lu: %s: unterminated transform source string",
646 p = compile_delimited(--p, new);
648 errx(1, "%lu: %s: unterminated transform target string",
651 if (strlen(new) != strlen(old))
652 errx(1, "%lu: %s: transform strings are not the same length",
654 /* We assume characters are 8 bits */
655 if ((lt = malloc(UCHAR_MAX)) == NULL)
657 for (i = 0; i <= UCHAR_MAX; i++)
659 for (op = old, np = new; *op; op++, np++)
660 lt[(u_char)*op] = *np;
666 * Compile the text following an a or i command.
671 int asize, esc_nl, size;
672 char *text, *p, *op, *s;
673 char lbuf[_POSIX2_LINE_MAX + 1];
675 asize = 2 * _POSIX2_LINE_MAX + 1;
676 if ((text = malloc(asize)) == NULL)
679 while (cu_fgets(lbuf, sizeof(lbuf), NULL)) {
680 op = s = text + size;
683 for (esc_nl = 0; *p != '\0'; p++) {
684 if (*p == '\\' && p[1] != '\0' && *++p == '\n')
693 if (asize - size < _POSIX2_LINE_MAX + 1) {
695 if ((text = realloc(text, asize)) == NULL)
700 if ((p = realloc(text, size + 1)) == NULL)
706 * Get an address and return a pointer to the first character after
707 * it. Fill the structure pointed to according to the address.
717 case '\\': /* Context address */
720 case '/': /* Context address */
721 p = compile_re(p, &a->u.r);
723 errx(1, "%lu: %s: unterminated regular expression", linenum, fname);
727 case '$': /* Last line */
731 case '0': case '1': case '2': case '3': case '4':
732 case '5': case '6': case '7': case '8': case '9':
734 a->u.l = strtol(p, &end, 10);
737 errx(1, "%lu: %s: expected context address", linenum, fname);
744 * Return a copy of all the characters up to \n or \0.
756 for (start = s; *s != '\0' && *s != '\n'; ++s)
757 ws = isspace((unsigned char)*s);
760 warnx("%lu: %s: whitespace after %s", linenum, fname, ctype);
762 if ((p = malloc(len)) == NULL)
764 return (memmove(p, start, len));
768 * Convert goto label names to addresses, and count a and r commands, in
769 * the given subset of the script. Free the memory used by labels in b
770 * and t commands (but not by :).
772 * TODO: Remove } nodes
776 struct s_command *cp, *end;
779 for (; cp != end; cp = cp->next)
787 /* Resolve branch target. */
792 if ((cp->u.c = findlabel(cp->t)) == NULL)
793 errx(1, "%lu: %s: undefined label '%s'", linenum, fname, cp->t);
797 /* Do interior commands. */
798 fixuplabel(cp->u.c, cp->next);
804 * Associate the given command label for later lookup.
808 struct s_command *cp;
810 struct labhash **lhp, *lh;
814 for (h = 0, p = (u_char *)cp->t; (c = *p) != 0; p++)
815 h = (h << 5) + h + c;
816 lhp = &labels[h & LHMASK];
817 for (lh = *lhp; lh != NULL; lh = lh->lh_next)
818 if (lh->lh_hash == h && strcmp(cp->t, lh->lh_cmd->t) == 0)
819 errx(1, "%lu: %s: duplicate label '%s'", linenum, fname, cp->t);
820 if ((lh = malloc(sizeof *lh)) == NULL)
830 * Find the label contained in the command l in the command linked
831 * list cp. L is excluded from the search. Return NULL if not found.
833 static struct s_command *
841 for (h = 0, p = (u_char *)name; (c = *p) != 0; p++)
842 h = (h << 5) + h + c;
843 for (lh = labels[h & LHMASK]; lh != NULL; lh = lh->lh_next) {
844 if (lh->lh_hash == h && strcmp(name, lh->lh_cmd->t) == 0) {
853 * Warn about any unused labels. As a side effect, release the label hash
859 struct labhash *lh, *next;
862 for (i = 0; i < LHSZ; i++) {
863 for (lh = labels[i]; lh != NULL; lh = next) {
866 warnx("%lu: %s: unused label '%s'",
867 linenum, fname, lh->lh_cmd->t);